package com.application.tak.takapplication;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.application.tak.takapplication.data_access.CheckUsernameExists;
import com.application.tak.takapplication.data_access.Config;
import com.application.tak.takapplication.data_model.Student_V;
import com.application.tak.takapplication.interfaces.OnDBRequestFinished;
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.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
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.common.api.GoogleApiClient;
import com.google.android.gms.tasks.Task;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.ProcessingInstruction;

import java.security.spec.ECField;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by Aleksandra on 04.05.2017.
 */
public class actStudentLoginMain  extends Fragment {
    public ImageView go;
    public String name, email;
    private static final int RC_SIGN_IN = 9001;
    private static final int RC_SHARE_DIALOG = 8031;
    private static String KEY_IS_RESOLVING = "is_resolving";
    private static String KEY_SHOULD_RESOLVE = "should_resolving";
    private static String URL = "http://plis.google.com/u/0/+DelaroyStudios/post";
    private static final String LABEL_READ_MORE = "READ_MORE";
    GoogleSignInClient mGoogleSignInClient;
    CallbackManager callbackManager;
    Context ctx = null;


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

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        ctx = this.getContext();
        mGoogleSignInClient = GoogleSignIn.getClient(this.getContext(), gso);
        callbackManager = CallbackManager.Factory.create();
        Button fb = (Button) rootView.findViewById(R.id.buttonFacebook);
        Button google = (Button) rootView.findViewById(R.id.buttonGoogle);
        LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);

        loginButton.setReadPermissions(Arrays.asList(
                "public_profile", "email"));


            if (google != null)
                google.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        signIn();
                    }
                });


            if(fb!= null)
            {
                fb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Profile profile = Profile.getCurrentProfile().getCurrentProfile();
                        if (profile != null) {
                            getFbInfo();
                        } else {
                            loginButton.performClick();
                        }


                 }
                });



            }

        loginButton.registerCallback(callbackManager,
                new FacebookCallback < LoginResult > () {@Override
                public void onSuccess(LoginResult loginResult) {

                    String accessToken = loginResult.getAccessToken()
                            .getToken();

                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {@Override
                            public void onCompleted(JSONObject object,
                                                    GraphResponse response) {
                                try {
                                    String id = object.getString("id");

                                    CheckUsernameExistsInDB(1,id,null,object);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields",
                            "id,first_name,last_name,email");
                    request.setParameters(parameters);
                    request.executeAsync();
                }

                    @Override
                    public void onCancel() {
                        System.out.println("onCancel");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        System.out.println("onError");
                        Log.v("LoginActivity", exception.getCause().toString());
                    }
                });


        return rootView;
    }


    private void signIn() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this.getContext());
        if (account != null)
        {

            CheckUsernameExistsInDB(0,account.getId(),account,null);
        }
        else{

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

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

        //for google
        if (requestCode == RC_SIGN_IN)
        {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    //0- google, 1-facebook
    void CheckUsernameExistsInDB(Integer logInType, String id, GoogleSignInAccount googleAccount, JSONObject fbAccount)
    {
        String fullId = "";
        if(logInType == 0)
        {
            fullId = "G-"+id;
        }
        else if(logInType == 1)
        {
            fullId = "F-"+id;
        }
        CheckUsernameExists checker = new CheckUsernameExists(fullId, this.getContext(),1);
        checker.setDBRequestFinishedListener(new OnDBRequestFinished() {
            @Override
            public void onDBRequestFinished() {
                if (checker.dbResult != null) {
                    String msg = checker.dbResult.getMSG();
                    if (msg.contentEquals("Sukces")) {
                        if (checker.dbResult.getRESULT() > 0) {
                            Toast.makeText(ctx,"Użytkownik jest już zarejestrowany w bazie!",Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        } else {
                            if(logInType == 0 && googleAccount != null)
                            {
                            GoogleCreateStudent(googleAccount.getEmail(),googleAccount.getId(),googleAccount.getGivenName(), googleAccount.getFamilyName());
                            }
                            if(logInType == 1 && fbAccount != null)
                            {
                                try {
                                    String id = fbAccount.getString("id");
                                    String first_name = fbAccount.getString("first_name");
                                    String last_name = fbAccount.getString("last_name");

                                    String email = "";
                                    if (fbAccount.has("email")) {
                                        email = fbAccount.getString("email");
                                    }

                                    FacebookCreateStudent(email, id, first_name, last_name);
                                }
                                catch(Exception ex)
                                {
                                    Config.LoggedInStudent = null;
                                    ex.printStackTrace();
                                }

                            }
                        }
                    }
                }
            }
        });
    }

    private void getFbInfo() {
        GraphRequest request = GraphRequest.newMeRequest(
                AccessToken.getCurrentAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        try {
                            if(object.has("id")) {
                                String id = object.getString("id");

                                CheckUsernameExistsInDB(1, id, null, object);
                            }
                            else
                            {
                                Toast.makeText(ctx,"Nastąpił problem z zalogowaniem się przez interfejs FB.\nSpróbuj ponownie później",Toast.LENGTH_LONG).show();
                            }

                        } catch (JSONException e) {
                            Config.LoggedInStudent = null;
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,first_name,last_name,email");
        request.setParameters(parameters);
        request.executeAsync();
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            CheckUsernameExistsInDB(0,account.getId(),account, null);
        } catch (ApiException e) {
            Config.LoggedInStudent = null;
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());

        }
    }

    private void GoogleCreateStudent(String email, String id, String fname, String lname)
    {
        Config.LoggedInStudent = new Student_V();

        Config.LoggedInStudent.set_Username(email);
        Config.LoggedInStudent.set_FName(fname);
        Config.LoggedInStudent.set_LName(lname);
        Config.LoggedInStudent.set_ExternAppId("G-"+id);
        ((actStudentLogin)getActivity()).SetCurrentItem(1);
    }

    private void FacebookCreateStudent(String email, String id, String fname, String lname)
    {
        Config.LoggedInStudent = new Student_V();

        Config.LoggedInStudent.set_Username(email);
        Config.LoggedInStudent.set_FName(fname);
        Config.LoggedInStudent.set_LName(lname);
        Config.LoggedInStudent.set_ExternAppId("F-"+id);
        ((actStudentLogin)getActivity()).SetCurrentItem(1);
    }


}