package com.epson.iprint.storage.onedrive;

import android.app.Activity;
import android.content.Context;
import com.epson.iprint.storage.SecureKeyStore;
import com.onedrive.sdk.authentication.IAuthenticator;
import com.onedrive.sdk.authentication.MSAAuthenticator;
import com.onedrive.sdk.concurrency.ICallback;
import com.onedrive.sdk.core.ClientException;
import com.onedrive.sdk.core.DefaultClientConfig;
import com.onedrive.sdk.extensions.IOneDriveClient;
import com.onedrive.sdk.extensions.OneDriveClient;

public class OneDriveAuthenticator {
    protected static final String TAG = "OneDriveAuthenticator";

    public interface OnOneDriveAuthenticatorListener {
        void onNotifyOneDriveClient(IOneDriveClient iOneDriveClient);
    }

    public static void getOneDriveClient(Activity activity, final OnOneDriveAuthenticatorListener onOneDriveAuthenticatorListener) {
        new OneDriveClient.Builder().fromConfig(DefaultClientConfig.createWithAuthenticator(getMSAAuthenticator(activity))).loginAndBuildClient(activity, new ICallback<IOneDriveClient>() {
            public void success(IOneDriveClient iOneDriveClient) {
                IAuthenticator authenticator;
                if (!(iOneDriveClient == null || (authenticator = iOneDriveClient.getAuthenticator()) == null)) {
                    OneDriveClient.saveToken(authenticator.getAccountInfo());
                }
                OnOneDriveAuthenticatorListener onOneDriveAuthenticatorListener = onOneDriveAuthenticatorListener;
                if (onOneDriveAuthenticatorListener != null) {
                    onOneDriveAuthenticatorListener.onNotifyOneDriveClient(iOneDriveClient);
                }
            }

            public void failure(ClientException clientException) {
                clientException.printStackTrace();
                OnOneDriveAuthenticatorListener onOneDriveAuthenticatorListener = onOneDriveAuthenticatorListener;
                if (onOneDriveAuthenticatorListener != null) {
                    onOneDriveAuthenticatorListener.onNotifyOneDriveClient((IOneDriveClient) null);
                }
            }
        });
    }

    private static MSAAuthenticator getMSAAuthenticator(final Context context) {
        return new MSAAuthenticator() {
            public String getClientId() {
                return getMicrosoftAccountForOneDrive(context);
            }

            public String[] getScopes() {
                return new String[]{"onedrive.readwrite", "offline_access"};
            }

            private String getMicrosoftAccountForOneDrive(Context context) {
                return new SecureKeyStore().getApiKeyD(context);
            }
        };
    }
}
