package org.deke.risk.riskahead.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
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 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 final static String TAG = FacebookButtonFragment.class.getSimpleName();

    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(@NonNull 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();
        callbackManager = CallbackManager.Factory.create();
        initFacebookButton();
    }

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

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

        btnLoginFB.setOnClickListener(v -> {
            LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
            Activity activity = getActivity();
            if(activity != null){
                LoginManager.getInstance().logInWithReadPermissions(activity, Arrays.asList("public_profile", "email"));
            }else{
                FirebaseCrashlytics.getInstance().log("Could not get activity when initializing the facebook button");
            }
        });

        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 activity = (LoginActivity) getActivity();
                        if(activity != null){
                            activity.showMessage("Facebook LogIn canceled. Please use E-Mail instead.");
                        }else{
                            FirebaseCrashlytics.getInstance().log("Could not get activity for showing onCancel message");
                        }
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Log.d("FB","OnError: " + exception.toString());
                        LoginActivity activity = (LoginActivity) getActivity();
                        if(activity != null){
                            activity.showMessage("Could not log in with Facebook. Please use E-Mail instead or try again later.");
                        }else{
                            FirebaseCrashlytics.getInstance().log("Could not get activity for showing onError message");
                        }
                    }
                });
    }

    private void getUserMailAndLogin(AccessToken accesstoken){
        GraphRequest request = GraphRequest.newMeRequest(accesstoken, (objects, response) -> {
            try {
                LoginActivity activity = (LoginActivity) getActivity();
                if(activity != null){
                    activity.handleSocialMediaLogin(objects.getString("id"), "facebook", objects.getString("first_name"), objects.getString("email"));
                }else{
                    FirebaseCrashlytics.getInstance().log("Could not get activity for handleSocialMediaLogin");
                }
            } catch (JSONException e) {
                FirebaseCrashlytics.getInstance().log("Exception caught: " + e);
                FirebaseCrashlytics.getInstance().recordException(e);
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,first_name,last_name,email");
        request.setParameters(parameters);
        request.executeAsync();
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}
