package com.carpoolsophia;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import butterknife.InjectView;
import butterknife.Views;

import com.carpoolsophia.gcloudApi.model.CarpoolSophiaUser;
import com.carpoolsophia.service.CarpoolSophiaUserService;
import com.carpoolsophia.service.ProfileService;
import com.facebook.AccessToken;
import com.facebook.AccessTokenUtils;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;

public class ProfileFragment extends Fragment {

  private final static String CLASSNAME = ProfileFragment.class.getSimpleName();

  @InjectView(R.id.TestLoadFromFB)
  Button testLoadFromFbBtn;

  @InjectView(R.id.profile_firstName)
  EditText profileFirstName;

  @InjectView(R.id.profile_lastName)
  EditText profileLastName;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile_fragment, container, false);
    Views.inject(this, view);

    return view;
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    final ProfileFragment finalThis = this;
    testLoadFromFbBtn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        Log.w(ProfileFragment.class.getSimpleName(), "loadFromFB");
        CarpoolSophiaUser user;
        try {
          user = (new LoadUserFromFbTask(finalThis).execute()).get();
          if (user != null) {
            // Log.w(getClass().getSimpleName(),
            // "user loaded: "+ModelToJSONParseAdapter.toJSONParse(user));
            profileFirstName.setText(user.getFirstName());
            profileLastName.setText(user.getLastName());
          }
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (ExecutionException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

      }
    });

  }

  public void updateProfileInfo(View btn) {
    Log.w(getClass().getSimpleName(), "updateProfileInfo");
  }

  private class LoadUserFromFbTask extends
      AsyncTask<CarpoolSophiaUser, Void, CarpoolSophiaUser> {
    private ProfileFragment profileFragment;

    public LoadUserFromFbTask(ProfileFragment fragment) {
      super();
      this.profileFragment = fragment;
    }

    @SuppressWarnings("serial")
    protected CarpoolSophiaUser doInBackground(final CarpoolSophiaUser... users) {
      CarpoolSophiaUser user = CarpoolSophiaUserService.get()
          .getCurrentCSuser();
      AccessToken accessToken = AccessTokenUtils.deserializeToken(user
          .getAccessToken());

      GraphRequest request = GraphRequest.newMeRequest(accessToken,
          new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
              // Log.d(CLASSNAME, "JSONobject: " + object);
              // Log.d(CLASSNAME, "GraphResponse #1: " +
              // response.getRawResponse());
            }
          });
      GraphResponse response = request.executeAndWait();
      Log.d(CLASSNAME, "GraphResponse #2: " + response.getRawResponse());

      CarpoolSophiaUser userFromFB = new CarpoolSophiaUser();
      try {
        userFromFB.setFirstName(response.getJSONObject()
            .getString("first_name"));
        userFromFB.setLastName(response.getJSONObject().getString("last_name"));
      } catch (JSONException e) {
        e.printStackTrace();
      }

      ProfileService.get().refreshCSUser(user, userFromFB);
      return user;
    }

    @Override
    protected void onPostExecute(CarpoolSophiaUser result) {
      super.onPostExecute(result);

    }

  }

}
