package com.pixelnx.sam.jobportal;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.pixelnx.sam.jobportal.Activity.ForgotPasswordActivity;
import com.pixelnx.sam.jobportal.Activity.RecruiterDashboardActivity;
import com.pixelnx.sam.jobportal.Activity.SeekerDashboardActivity;
import com.pixelnx.sam.jobportal.DTOCI.ModelLanguageDTO;
import com.pixelnx.sam.jobportal.DTOCI.ModelSeekerLogin;
import com.pixelnx.sam.jobportal.network.NetworkManager;
import com.pixelnx.sam.jobportal.preferences.SharedPrefrence;
import com.pixelnx.sam.jobportal.utils.AppConstans;
import com.pixelnx.sam.jobportal.utils.Consts;
import com.pixelnx.sam.jobportal.utils.CustomButton;
import com.pixelnx.sam.jobportal.utils.CustomEdittext;
import com.pixelnx.sam.jobportal.utils.CustomTextHeader;
import com.pixelnx.sam.jobportal.utils.CustomTextview;
import com.pixelnx.sam.jobportal.utils.CustomTextviewBold;
import com.pixelnx.sam.jobportal.utils.ProjectUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import belka.us.androidtoggleswitch.widgets.BaseToggleSwitch;
import belka.us.androidtoggleswitch.widgets.ToggleSwitch;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
    private RadioGroup radioGroup;
    private CustomTextHeader tvEmail;
    private RadioButton RBSeeker, RBRecruiter;
    private CustomEdittext etEmail, etPassword;
    private CustomButton loginBtn;
    private CustomTextview tvCreatnewaccount, tvForgotpass, tvGuestLogin;
    private Context mContext;
    private CardView cvGoogleLogin;
    private SharedPrefrence prefrence;
    private CustomTextviewBold tvyrEmail, tvpassword;
    private ToggleSwitch toggle_switch;
    private TelephonyManager telephonyManager;
    SharedPreferences userDetails;
    ModelLanguageDTO modelLanguageDTO;
    private AdView mAdView;
    View adMobView;
    private String errorMSG = "";
    int count = 3;
    private static Locale locale = new Locale(Consts.ENGLIShLANGUAGE);
    private static final int RC_SIGN_IN = 007;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = LoginActivity.this;
        prefrence = SharedPrefrence.getInstance(mContext);

        userDetails = LoginActivity.this.getSharedPreferences("MyPrefs", MODE_PRIVATE);
        Log.e("tokensss", userDetails.getString(Consts.TOKAN, ""));
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
      //  Log.e("LOGIN_ID", "my id: " + telephonyManager.getDeviceId());

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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
        init();
    }

    private void init() {
        etEmail = (CustomEdittext) findViewById(R.id.etEmail);
        etPassword = (CustomEdittext) findViewById(R.id.etPassword);
        toggle_switch = (ToggleSwitch) findViewById(R.id.toggle_switch);
        tvyrEmail = (CustomTextviewBold) findViewById(R.id.tvyrEmail);
        tvpassword = (CustomTextviewBold) findViewById(R.id.tvpassword);
        tvEmail = (CustomTextHeader) findViewById(R.id.tvEmail);

        String first = LoginActivity.this.getResources().getString(R.string.do_nt_have);
        String next = "<font color='#7062E9'><b>" + getResources().getString(R.string.sign_up) + "</b></font>";
        String guest = "<font color='#7062E9'><u><b>" + getResources().getString(R.string.guest_login_d) + "</b></u></font>";

        adMobView = findViewById(R.id.adMobView);
        cvGoogleLogin = (CardView) findViewById(R.id.cvGoogleLogin);
        tvForgotpass = (CustomTextview) findViewById(R.id.tvForgotpass);
        tvCreatnewaccount = (CustomTextview) findViewById(R.id.tvCreatnewaccount);
        tvGuestLogin = (CustomTextview) findViewById(R.id.tvGuestLogin);
        // mAdView = (AdView) findViewById(R.id.adView);
        tvCreatnewaccount.setText(Html.fromHtml(first + next));
        tvGuestLogin.setText(Html.fromHtml(guest));

        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        RBSeeker = (RadioButton) findViewById(R.id.RBSeeker);
        RBRecruiter = (RadioButton) findViewById(R.id.RBRecruiter);
        loginBtn = (CustomButton) findViewById(R.id.loginBtn);


        getLanguage();
        loginBtn.setOnClickListener(this);
        tvForgotpass.setOnClickListener(this);
        tvCreatnewaccount.setOnClickListener(this);
        tvGuestLogin.setOnClickListener(this);
        RBSeeker.setOnClickListener(this);
        RBRecruiter.setOnClickListener(this);
        cvGoogleLogin.setOnClickListener(this);


        if (prefrence.getBooleanValue(Consts.SECONDLANGUAGE)) {
            toggle_switch.setCheckedTogglePosition(1);
        } else toggle_switch.setCheckedTogglePosition(0);

        toggle_switch.setOnToggleSwitchChangeListener(new BaseToggleSwitch.OnToggleSwitchChangeListener() {
            @Override
            public void onToggleSwitchChangeListener(int position, boolean isChecked) {

                if (position == 1) {
                    prefrence.setValue(Consts.SECONDLANGUAGE, Consts.ANOTHER_LANGUAGE);
              /*      locale = new Locale(languageHindi);
                    Locale.setDefault(locale);
                    Configuration config = new Configuration();
                    config.locale = locale;
                    LoginActivity.this.getResources().updateConfiguration(config, LoginActivity.this.getResources().getDisplayMetrics());
                    Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);*/
                    prefrence.setBooleanValue(Consts.SECONDLANGUAGE, true);
                    locale = new Locale(Consts.SECONDLANGUAGE);
                    Resources res = getResources();
                    DisplayMetrics dm = res.getDisplayMetrics();
                    Configuration conf = res.getConfiguration();
                    conf.locale = locale;
                    res.updateConfiguration(conf, dm);
                    Intent refresh = new Intent(LoginActivity.this, LoginActivity.class);
                    startActivity(refresh);
                    finish();
                }
                if (position == 0) {
                    prefrence.setBooleanValue(Consts.SECONDLANGUAGE, false);
                    prefrence.setValue(Consts.ENGLIShLANGUAGE, Consts.ANOTHER_LANGUAGE);
                    locale = new Locale(Consts.ENGLIShLANGUAGE);
                    Locale.setDefault(locale);
                    Configuration config = new Configuration();
                    config.locale = locale;
                    LoginActivity.this.getResources().updateConfiguration(config, LoginActivity.this.getResources().getDisplayMetrics());

                    Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                submitForm();
                break;
            case R.id.tvForgotpass:
                startActivity(new Intent(LoginActivity.this, ForgotPasswordActivity.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
                break;
            case R.id.tvCreatnewaccount:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
                break;
            case R.id.tvGuestLogin:
                Intent in = new Intent(mContext, SeekerDashboardActivity.class);
                in.putExtra(Consts.TAG_GUEST, 2);
                startActivity(in);
                overridePendingTransition(R.anim.enter, R.anim.exit);
                finish();
                break;
            case R.id.RBSeeker:
                tvGuestLogin.setVisibility(View.VISIBLE);
                break;
            case R.id.RBRecruiter:
                tvGuestLogin.setVisibility(View.GONE);
                break;
            case R.id.cvGoogleLogin:
                signIn();
                break;
        }
    }


    public void submitForm() {
        if (!ValidateEmail()) {
            return;
        } else if (!validatePassword()) {
            return;
        } else if (!SelectType()) {
            return;
        } else {
            login();
        }
    }


    public boolean ValidateEmail() {
        if (!ProjectUtils.IsEmailValidation(etEmail.getText().toString().trim())) {
            etEmail.setError(errorMSG);
            etEmail.requestFocus();
            return false;
        }
        return true;
    }

    public boolean validatePassword() {
        if (etPassword.getText().toString().trim().equalsIgnoreCase("")) {
            etPassword.setError(getResources().getString(R.string.val_new_pas));
            etPassword.requestFocus();
            return false;
        } else {
            if (!ProjectUtils.IsPasswordValidation(etPassword.getText().toString().trim())) {
                etPassword.setError(errorMSG);
                etPassword.requestFocus();
                return false;
            } else {
                return true;
            }
        }
    }

    public boolean SelectType() {

        if (radioGroup.getCheckedRadioButtonId() == -1) {
            Toast.makeText(getApplicationContext(), errorMSG, Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    public void login() {

        if (NetworkManager.isConnectToInternet(mContext)) {
            seekerlogin();
        } else {
            ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_connection));
        }
   /* if (RBRecruiter.isChecked()) {
            if (NetworkManager.isConnectToInternet(mContext)) {
                recruiterlogin();
            } else {
                ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_connection));
            }
        }*/
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.d("LOGIN", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            Log.e("LOGIN", "display name: " + acct.getDisplayName());

            String personName = acct.getDisplayName();
//            String personPhotoUrl = acct.getPhotoUrl().toString();
            //          String email = acct.getEmail();

            Log.e("LOGIN", "Name: " + personName + ", email: " + acct.getEmail());

            updateUI(acct);
        } else {
            // Signed out, show unauthenticated UI.

            Log.e("LOGIN", "Fail");
        }
    }

    private void updateUI(GoogleSignInAccount acct) {


        storeGoogleInfo(acct);

    }


    private void storeGoogleInfo(final GoogleSignInAccount acct) {
        ProjectUtils.showProgressDialog(mContext, false, "Please wait...");
        StringRequest googleRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.GOOGLE_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();

                        ProjectUtils.pauseProgressDialog();
                        Log.e("Seeker_login", response.toString());
                        try {

                            ModelSeekerLogin userSeekerDTO = new ModelSeekerLogin();
                            userSeekerDTO = new Gson().fromJson(response, ModelSeekerLogin.class);
                            if (userSeekerDTO.getStaus().equalsIgnoreCase("true")) {
                                prefrence.setUserDTO(userSeekerDTO, AppConstans.SEEKERDTO);
                                if (RBSeeker.isChecked()) {
                                    //   s = "seeker";
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_SEEKER, true);
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_RECRUITER, false);
                                    Intent in = new Intent(mContext, SeekerDashboardActivity.class);
                                    in.putExtra(Consts.TAG_GUEST, 1);
                                    startActivity(in);
                                    finish();

                                } else {
                                    //    s = "recruiter";
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_SEEKER, false);
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_RECRUITER, true);
                                    Intent in = new Intent(mContext, RecruiterDashboardActivity.class);
                                    in.putExtra(Consts.TAG_GUEST, 1);
                                    startActivity(in);
                                    finish();

                                }
                            } else if (userSeekerDTO.getStaus().equalsIgnoreCase("false")) {
                                if (userSeekerDTO.getMessage().equalsIgnoreCase("please pay")) {
                                    ProjectUtils.showDialog(LoginActivity.this, userSeekerDTO.getData().getEmail(), "");
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        Log.d("LOGIN_ERROR_SEEKER", "Login Error:" + error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                if (RBSeeker.isChecked())
                    params.put(AppConstans.TYPE, "seeker");
                else
                    params.put(AppConstans.TYPE, "recruiter");
                if (acct.getPhotoUrl().toString() != null) {
                    params.put(AppConstans.IMG, acct.getPhotoUrl().toString());
                }
                if (acct.getId() != null)
                    params.put(AppConstans.GOOGLE_ID, acct.getId());
                if (acct.getEmail() != null)
                    params.put(AppConstans.EMAIL, acct.getEmail());
                if (acct.getDisplayName() != null)
                    params.put(AppConstans.NAME, acct.getDisplayName());
                params.put(AppConstans.TOKEN, userDetails.getString(Consts.TOKAN, ""));
                Log.e("google_login", params.toString());
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(googleRequest);
    }

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

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    public void seekerlogin() {
        ProjectUtils.showProgressDialog(mContext, false, "Please wait...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();
                        try {
                            JSONObject object = new JSONObject(response);
                            if (object.getString("staus").equalsIgnoreCase("false")) {
                                ProjectUtils.showToast(mContext, object.getString("message"));
                                return;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ProjectUtils.pauseProgressDialog();
                        Log.e("Seeker_login", response.toString());
                        try {
                            ModelSeekerLogin userSeekerDTO = new ModelSeekerLogin();
                            userSeekerDTO = new Gson().fromJson(response, ModelSeekerLogin.class);
                            if (userSeekerDTO.getStaus().equalsIgnoreCase("true")) {
                                ProjectUtils.showToast(mContext, userSeekerDTO.getMessage());
                                prefrence.setUserDTO(userSeekerDTO, AppConstans.SEEKERDTO);
                                if (userSeekerDTO.getData().getPs().equalsIgnoreCase("r")) {
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_SEEKER, false);
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_RECRUITER, true);
                                    Intent in = new Intent(mContext, RecruiterDashboardActivity.class);
                                    in.putExtra(Consts.TAG_GUEST, 1);
                                    startActivity(in);
                                    finish();
                                } else {
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_SEEKER, true);
                                    prefrence.setBooleanValue(Consts.IS_REGISTER_RECRUITER, false);
                                    Intent in = new Intent(mContext, SeekerDashboardActivity.class);
                                    in.putExtra(Consts.TAG_GUEST, 1);
                                    startActivity(in);
                                    finish();
                                }
                            } else {
                                prefrence.setBooleanValue(Consts.IS_REGISTER_SEEKER, false);
                                prefrence.setBooleanValue(Consts.IS_REGISTER_RECRUITER, false);
                                ProjectUtils.showToast(mContext, userSeekerDTO.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        Log.d("LOGIN_ERROR_SEEKER", "Login Error:" + error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                String s = "";

                if (RBSeeker.isChecked()) {
                    s = "seeker";
                } else {
                    s = "recruiter";
                }
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.TYPE, s);
                params.put(AppConstans.EMAIL, ProjectUtils.getEditTextValue(etEmail));
                params.put(AppConstans.PASSWORD, ProjectUtils.getEditTextValue(etPassword));
                params.put(AppConstans.TOKEN, userDetails.getString(Consts.TOKAN, ""));
                Log.e("seeker_login", params.toString());
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }


    @Override
    public void onBackPressed() {
        clickClose();
    }

    public void clickClose() {
        new AlertDialog.Builder(this)
                .setIcon(R.mipmap.logo)
                .setTitle(getString(R.string.app_name))
                .setMessage(getString(R.string.msg_dialog))
                .setPositiveButton(getString(R.string.yes_dialog), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent i = new Intent();
                        i.setAction(Intent.ACTION_MAIN);
                        i.addCategory(Intent.CATEGORY_HOME);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);
                        finish();
                    }
                })
                .setNegativeButton(getString(R.string.no_dialog), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }


    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }

    private void getLanguage() {
        ProjectUtils.pauseProgressDialog();
        ProjectUtils.showProgressDialog(mContext, false, "PLease Wait");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, AppConstans.BASE_URL +AppConstans.LANGUAGE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();
                        try {
                            ProjectUtils.pauseProgressDialog();
                            modelLanguageDTO = new Gson().fromJson(response, ModelLanguageDTO.class);
                            prefrence.setLanguage(modelLanguageDTO, AppConstans.LANGUAGE);
                            tvpassword.setText(modelLanguageDTO.getData().getPassword_login());
                            tvyrEmail.setText(modelLanguageDTO.getData().getEmail_login());
                            loginBtn.setText(modelLanguageDTO.getData().getLogin());
                            tvForgotpass.setText(modelLanguageDTO.getData().getForgot_password());
                            RBSeeker.setText(modelLanguageDTO.getData().getLogin_option1());
                            RBRecruiter.setText(modelLanguageDTO.getData().getLogin_option2());
                            tvCreatnewaccount.setText(modelLanguageDTO.getData().getRegister_msg());
                            tvGuestLogin.setText(modelLanguageDTO.getData().getGuest_keyword());
                            tvEmail.setText(modelLanguageDTO.getData().getLogin_keyword());
                            errorMSG = modelLanguageDTO.getData().getFill_keyword();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        while (count >= 0) {
                            count--;
                            getLanguage();
                            Log.d("F", "onConnectionFailed:" + count);
                        }
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        ProjectUtils.pauseProgressDialog();
        Log.d("F", "onConnectionFailed:" + connectionResult);
    }
}