package com.udacity.gradle.builditbigger;

import android.content.Context;
import android.os.AsyncTask;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.udacity.gradle.buiditbigger.backend.myApi.MyApi;

import java.io.IOException;

/**
 * Created by Pablo on 26/02/16.
 */
public class EndpointsAsyncTask extends AsyncTask<Context, Void, String> {
    private static MyApi myApiService = null;
    private final JokeListener mListener;

    public EndpointsAsyncTask(JokeListener listener) {
        mListener = listener;
    }

    @Override
    protected String doInBackground(Context... params) {
        if (myApiService == null) {  // Only do this once
            MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null)
                    // options for running against local devappserver
                    // - 10.0.2.2 is localhost's IP address in Android emulator
                    // - turn off compression when running against local devappserver
                    .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                    .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                        @Override
                        public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                            abstractGoogleClientRequest.setDisableGZipContent(true);
                        }
                    });
            // end options for devappserver

            myApiService = builder.build();
        }

        try {
            return myApiService.getAJoke().execute().getTheJoke();
        } catch (IOException e) {
            return e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        mListener.onJokeReceived(result);
    }
}
@@ -96,16 +96,41 @@
 yncTask;
+%0Aimport android.util.Log;
 %0A%0Aimport
@@ -716,16 +716,91 @@
 tener;%0A%0A
+    private final static String TAG = EndpointsAsyncTask.class.getName();%0A%0A
     publ
@@ -2079,29 +2079,68 @@
     
-return e.getMessage()
+Log.e(TAG, e.getLocalizedMessage());%0A            return null
 ;%0A  

return null in case of no connection