package org.deke.risk.riskahead.fragment;

import android.content.Context;
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.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;

import org.deke.risk.riskahead.LoginActivity;
import org.deke.risk.riskahead.R;

/**
 *
 * (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 GooglePlusButtonFragment extends Fragment{

    public static final int RC_SIGN_IN = 0;
    private static final String TAG = GooglePlusButtonFragment.class.getSimpleName();

    GoogleSignInClient mGoogleSignInClient;

    private Context mContext;
    private LoginActivity mActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (LoginActivity) getActivity();
        if(mActivity != null){
            mContext = mActivity.getApplicationContext();
        }else{
            FirebaseCrashlytics.getInstance().log("Could not retrieve activity for Google+ onCreate Method");
        }
    }

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

        BootstrapButton btnSignIn = view.findViewById(R.id.btn_login_gp);
        btnSignIn.setOnClickListener(v -> performClickAction());

        return view;
    }

    private void performClickAction() {
        Log.d(TAG,"Click on Google+ Button performed");
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(mContext);

        if(account != null){
            Log.d(TAG, "User already logged in - handle social media login");
            mActivity.handleSocialMediaLogin(account.getId(),"google",account.getDisplayName(),account.getEmail());
        }else{
            Log.d(TAG, "User not logged in - log in to g+ now");
            signInWithGplus();
        }
    }

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

        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            GoogleSignInAccount account = handleSignInResult(task);
            if(account != null){
                mActivity.handleSocialMediaLogin(account.getId(),"google",account.getDisplayName(),account.getEmail());
            }else{
                FirebaseCrashlytics.getInstance().log("Could not handle G+ SignIn Result");
            }
        }
    }

    private GoogleSignInAccount handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            return completedTask.getResult(ApiException.class);
        } catch (ApiException e) {
            FirebaseCrashlytics.getInstance().log("signInResult:failed code=" + e.getStatusCode());
            return null;
        }
    }

    private void signInWithGplus() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestId()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(mContext, gso);

        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

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