package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cygnusa.hyperm.tooltip.Tooltip;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.UserResponse;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.HashMap;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginActivity extends AppCompatActivity {
    EditText mPasswordView, mEmailView;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    StorePreference storePreference;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        restService = ((MainApplication) getApplication()).getClient();
        mEmailView = findViewById(R.id.userName);
        mPasswordView = findViewById(R.id.password);
        storePreference = new StorePreference(this);
        TextView textView = findViewById(R.id.notRegistered);
        SpannableString loginText = new SpannableString("Signup");
        loginText.setSpan(new UnderlineSpan(), 0, loginText.length(), 0);
        textView.setText(loginText);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == 2276) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        findViewById(R.id.email_sign_in_button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        findViewById(R.id.notRegistered).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
            }
        });

        findViewById(R.id.info).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                String header = "-If you are dealer staff enter the SMPIN for registering and logging into the system\n" +
                        "\n-If you are HYPER-M staff enter your Employee ID for registering and logging into the system";
                View mView = LayoutInflater.from(LoginActivity.this).inflate(R.layout.login_tooltip_text, null);
                TextView text = mView.findViewById(R.id.text11);
                text.setText(header);
                Tooltip.TooltipView tooltip = Tooltip.make(LoginActivity.this,
                        new Tooltip.Builder(101)
                                .anchor(view, Tooltip.Gravity.TOP)
                                .closePolicy(new Tooltip.ClosePolicy()
                                        .insidePolicy(true, false)
                                        .outsidePolicy(true, false), 0)
                                .activateDelay(300)
                                .withStyleId(R.style.ToolTipLayoutCustomStyle)
                                .showDelay(300)
                                .text("")
                                .setBgColor(getResources().getColor(R.color.bg_color))
                                .view(mView)
                                .maxWidth(300)
                                .withArrow(true)
                                .build()
                );
                tooltip.setTextColor(Color.WHITE);
                tooltip.show();
            }
        });
        TextView mTextView = findViewById(R.id.forgotPassword);
        String udata = mTextView.getText().toString().trim();
        SpannableString content = new SpannableString(udata);
        content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
        mTextView.setText(content);
        mTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(), ForgotPasswordActivity.class));
            }
        });
        findViewById(R.id.faq).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, FaqActivity.class));
                finish();
            }
        });

        findViewById(R.id.faq1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                findViewById(R.id.faq).performClick();
            }
        });
    }


    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    private void attemptLogin() {
        String email = mEmailView.getText().toString().trim();
        String password = mPasswordView.getText().toString().trim();

        boolean cancel = false;
        View focusView = null;
        if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) {
            GlobalData.showToast(getBaseContext(), "Please fill in all necessary fields", Toast.LENGTH_SHORT).show();
            focusView = mEmailView;
            cancel = true;
        } else if (TextUtils.isEmpty(email)) {
            GlobalData.showToast(getBaseContext(), "Please enter the SMPIN", Toast.LENGTH_SHORT).show();
            focusView = mEmailView;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            GlobalData.showToast(getBaseContext(), "Please enter the password", Toast.LENGTH_SHORT).show();
            focusView = mPasswordView;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            if (new UtilService().isNetworkAvailable(LoginActivity.this)) {
                progressDialog = new TransparentProgressDialog(LoginActivity.this);
                progressDialog.show();

                try {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("username", email);
                    map.put("password", password);
                    restService.login(map).enqueue(new Callback<UserResponse>() {
                        @Override
                        public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                            GlobalData.user = response.body();
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            if (GlobalData.user != null && GlobalData.user.getStatus() == 200) {
                                getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                        .edit().putString("FCM_TOKEN_ID", "").apply();
                                if (Build.VERSION.SDK_INT >= 23) {
                                    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                            == PackageManager.PERMISSION_GRANTED) {
                                        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                                                + "/" + ".HYPERM", "PDF");
                                        if (f1.exists()) {
                                            f1.delete();
                                        }
                                    }
                                } else {
                                    File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                                            + "/" + ".HYPERM", "PDF");
                                    if (f1.exists()) {
                                        f1.delete();
                                    }
                                }

                                GlobalData.sdb.delete("session", null, null);
                                preferences = getSharedPreferences("UserDetails",
                                        Context.MODE_PRIVATE);
                                if (!Objects.requireNonNull(preferences.getString("inputUsername", "")).trim()
                                        .equalsIgnoreCase(mEmailView.getText().toString().trim())) {
                                    GlobalData.sdb.delete("training", null, null);
                                    GlobalData.sdb.delete("assessment", null, null);
                                    GlobalData.sdb.delete("assessment_question", null, null);
                                    GlobalData.sdb.delete("assessment_answer", null, null);
                                    GlobalData.sdb.delete("notifications", null, null);
                                    GlobalData.sdb.delete("notification_readed", null, null);
                                    GlobalData.sdb.delete("notification_deleted", null, null);
                                    GlobalData.sdb.delete("banner", null, null);
                                    GlobalData.sdb.delete("topic", null, null);
                                    GlobalData.sdb.delete("topic_content", null, null);
                                }
                                editor = preferences.edit();
                                editor.putString("inputUsername", mEmailView.getText().toString().trim());
                                editor.putString("inputPassword", mPasswordView.getText().toString().trim());
                                editor.apply();
                                ((MainApplication) getApplication()).addAccessToken(String.format("Bearer %s", GlobalData.user.getAccess_token().trim()));
                                restService = ((MainApplication) getApplication()).getClient();
                                if (GlobalData.user.getData().getIs_first_login().trim().equalsIgnoreCase("1")) {
                                    startActivity(new Intent(getBaseContext(), SetNewPasswordActivity.class));
                                    finish();
                                } else if (GlobalData.user.getData().getIs_password_expired().trim().equalsIgnoreCase("1")) {
                                    GlobalData.showToast(LoginActivity.this, "Your password is expired, please create new password", Toast.LENGTH_SHORT).show();
                                    startActivity(new Intent(getBaseContext(), SetNewPasswordActivity.class));
                                    finish();
                                } else if (GlobalData.user.getData().getIs_profile_updated().equalsIgnoreCase("0")) {
                                    startActivity(new Intent(getBaseContext(), MainProfileActivity.class));
                                    finish();
                                } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
                                    GlobalData.showToast(getBaseContext(), "You don’t have required permission to log in to the STAR app", Toast.LENGTH_LONG).show();
                                } else {
                                    Gson gson = new Gson();
                                    JsonElement jsonElement = gson.toJsonTree(
                                            GlobalData.user, new TypeToken<UserResponse>() {
                                            }.getType());
                                    ContentValues values = new ContentValues();
                                    values.put("user", jsonElement.toString());
                                    GlobalData.sdb.insert("session", null, values);
                                    GlobalData.zmEmail = "none";
                                    GlobalData.rmEmail = "none";
                                    GlobalData.amEmail = "none";
                                    GlobalData.canLogout = false;
                                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                                            || GlobalData.user.getData().getRole().equalsIgnoreCase("6")
                                            || GlobalData.user.getData().getRole().equalsIgnoreCase("7")
                                            || GlobalData.user.getData().getRole().equalsIgnoreCase("3")
                                            || GlobalData.user.getData().getRole().equalsIgnoreCase("5")
                                            || GlobalData.user.getData().getRole().equalsIgnoreCase("14")) {
                                        storePreference.setBoolean(GlobalData.ISDSELOGIN, false);
                                        startActivity(new Intent(LoginActivity.this, AMHomeActivity.class));
                                        finish();
                                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("15")) {
                                        storePreference.setBoolean(GlobalData.ISDSELOGIN, false);
                                        startActivity(new Intent(LoginActivity.this, SEHomeActivity.class));
                                        finish();
                                    } else {
                                        storePreference.setBoolean(GlobalData.ISDSELOGIN, true);
                                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                        finish();
                                    }

                                }

                            } else if (GlobalData.user != null) {
                                GlobalData.showToast(getBaseContext(), GlobalData.user.getMessage(), Toast.LENGTH_SHORT).show();
                            } else if (response.errorBody() != null) {
                                Gson gson = new Gson();
                                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<UserResponse> call, Throwable t) {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);

    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(LoginActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    Objects.requireNonNull(activity.getCurrentFocus()).getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

