package de.lcs.wep.calendar;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * Created by Sönke Greve on 30.10.2014.
 */
public class Credential {

    public static Logger logger = LogManager.getLogger(Credential.class);

    private String accountId;
    private String apiUrl;
    private String p12;

    public static Credential fromProperties(Properties props) {
        String id = props.getProperty(Constants.PROP_KEY_GOOGLE_SERVICE_ACCOUNT_ID);
        String apiUrl = Constants.GOOGLE_CALENDAR_API_URL;
        String p12 = Constants.P12_AUTHENTICATION_FILENAME;

        Credential result = new Credential(id, apiUrl, p12);
        return result;
    }

    public Credential(String accountId, String apiUrl, String p12Filename) {
        this.accountId = accountId;
        this.apiUrl = apiUrl;
        this.p12 = p12Filename;
    }

    public GoogleCredential createGoogleCredential() {
        GoogleCredential result = null;
        try {
            NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = new GsonFactory();
            List<String> apiUrls = Arrays.asList(apiUrl);

            // connect to Google API's via service account (email address = AccountID, email address = AccountUser, p12 key = P12File, scope = calendar scopes from Google)
            GoogleCredential.Builder b = new GoogleCredential.Builder();
            b.setTransport(transport);
            b.setJsonFactory(jsonFactory);
            b.setServiceAccountId(accountId);
            b.setServiceAccountScopes(apiUrls);
            b.setServiceAccountPrivateKeyFromP12File(new File(p12)).build();
            result = b.build();
            // .setServiceAccountUser(props.getProperty("serviceaccountid")) - Do not set serviceAccountUser when using a serviceAccountId
            logger.debug("Google authentication with service account successful.");
        } catch (Exception e) {
            logger.error("Authentication for service account failed. Please review the configuration: ", e);
        }
        return result;
    }
}
