package org.deke.risk.riskahead.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginBehavior;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

import org.deke.risk.riskahead.LoginActivity;
import org.deke.risk.riskahead.R;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

/**
 *
 * (C) Copyright 2016 RiskAhead (http://www.riskahead.net)
 * Developer & Contributor: Dennis Thießen (dennis.thiessen@riskahead.net)
 * Date of Release: 10.02.2016
 *
 */
public class FacebookButtonFragment extends Fragment {

    private BootstrapButton btnLoginFB;
    CallbackManager callbackManager;
    OnFragmentInteractionListener mListener;
    View view;

    public FacebookButtonFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

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

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        FacebookSdk.sdkInitialize(getContext());
        callbackManager = CallbackManager.Factory.create();
        initFacebookButton();
    }

        @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);

    }

    private void initFacebookButton() {
        btnLoginFB = (BootstrapButton) view.findViewById(R.id.btn_login_fb);

        btnLoginFB.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
                LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "email"));
            }
        });

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        getUserMailAndLogin(loginResult.getAccessToken());
                    }

                    @Override
                    public void onCancel() {
                        Log.d("FB","OnCancel");
                        ((LoginActivity) getActivity()).showMessage("Facebook LogIn canceled. Please use E-Mail instead.");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Log.d("FB","OnError: " + exception.toString());
                        ((LoginActivity) getActivity()).showMessage("Could not log in with Facebook. Please use E-Mail instead or try again later.");
                    }
                });
    }

    private void getUserMailAndLogin(AccessToken accesstoken){
        GraphRequest request = GraphRequest.newMeRequest(accesstoken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject objects, GraphResponse response) {
                try {
                    ((LoginActivity) getActivity()).handleSocialMediaLogin(objects.getString("id"), "facebook", objects.getString("first_name"), objects.getString("email"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,first_name,last_name,email");
        request.setParameters(parameters);
        request.executeAsync();
    }
}
