package ext.SimpleGoogle;

import android.app.Activity;
import android.os.AsyncTask;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;

import java.io.IOException;

import ext.java.threading.Callback;

public class GetAccessTokenTask extends AsyncTask<Void, Void, String>
{
    private static final String SCOPE =
            "oauth2:https://www.googleapis.com/auth/userinfo.profile" + " " +
                    "https://www.googleapis.com/auth/userinfo.email" + " " +
                    "https://www.googleapis.com/auth/plus.login";

    private Activity _activity;
    private String _email;

    private IAccessTokenExceptionHandler _accessTokenExceptionHandler;
    private Callback<String> _onAccessTokenFetched;

    public GetAccessTokenTask(Activity activity, String name,
                              IAccessTokenExceptionHandler accessTokenExceptionHandler,
                              Callback<String> onAccessTokenFetched)
    {
        _activity = activity;
        _email = name;
        _accessTokenExceptionHandler = accessTokenExceptionHandler;
        _onAccessTokenFetched = onAccessTokenFetched;
    }

    @Override
    protected String doInBackground(Void... params)
    {
        try
        {
            return GoogleAuthUtil.getToken(_activity, _email, SCOPE);

        } catch (UserRecoverableAuthException userRecoverableException)
        {
            // GooglePlayServices.apk is either old, disabled, or not present
            // so we need to show the user some UI in the activity to recover.
            _accessTokenExceptionHandler.handleAccessTokenFetchException(userRecoverableException);

        } catch (GoogleAuthException fatalException)
        {
            // Some other type of unrecoverable exception has occurred.
            // Report and log the error as appropriate for your app.
        } catch (IOException e)
        {
            return null;
        }

        return null;
    }

    @Override
    protected void onPostExecute(String accessToken)
    {
        _onAccessTokenFetched.whenReady(accessToken);
    }
}
