package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MenuItem;
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.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;

import java.util.HashMap;
import java.util.regex.Pattern;

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


public class ChangePasswordActivity extends AppCompatActivity {
    EditText newPassword, confirmPassword, oldPassword;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z,A-Z]).{8,30})";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_change_password);
        GlobalData.openDatabase(ChangePasswordActivity.this);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));

        restService = ((MainApplication) getApplication()).getClient();
        newPassword = findViewById(R.id.newPassword);
        confirmPassword = findViewById(R.id.confirmPassword);
        oldPassword = findViewById(R.id.oldPassword);

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

//        Toolbar toolbar = findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        toolbar.setTitle("");
//        getSupportActionBar().setTitle("");
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        getSupportActionBar().setDisplayShowHomeEnabled(true);
       @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
//        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        ImageView imageView = findViewById(R.id.back_btn);
        imageView.setImageDrawable(backArrow);
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                overridePendingTransition(R.anim.animation_f_enter,
                        R.anim.animation_f_leave);
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

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

    private void attemptLogin() {
        String nPassword = newPassword.getText().toString().trim();
        String cPassword = confirmPassword.getText().toString().trim();
        String oPassword = oldPassword.getText().toString().trim();

        boolean cancel = false;
        View focusView = null;
        if (TextUtils.isEmpty(oPassword) && TextUtils.isEmpty(nPassword) && TextUtils.isEmpty(cPassword)) {
            GlobalData.showToast(getBaseContext(), "Please fill in all necessary fields.", Toast.LENGTH_SHORT).show();
            focusView = oldPassword;
            cancel = true;
        } else if (TextUtils.isEmpty(oPassword)) {
            GlobalData.showToast(getBaseContext(), "Please enter the old password", Toast.LENGTH_SHORT).show();
            focusView = oldPassword;
            cancel = true;
        } else if (TextUtils.isEmpty(nPassword)) {
            GlobalData.showToast(getBaseContext(), "Please enter the new password", Toast.LENGTH_SHORT).show();
            focusView = newPassword;
            cancel = true;
        } else if (TextUtils.isEmpty(cPassword)) {
            GlobalData.showToast(getBaseContext(), "Please enter the confirm password", Toast.LENGTH_SHORT).show();
            focusView = confirmPassword;
            cancel = true;
        } else if (!nPassword.equals(cPassword)) {
            GlobalData.showToast(getBaseContext(), "Password not matching", Toast.LENGTH_SHORT).show();
            focusView = confirmPassword;
            cancel = true;
        } else if (!Pattern.compile(PASSWORD_PATTERN).matcher(cPassword).matches()) {
            GlobalData.showToast(getBaseContext(), "The password must have at least 8 characters and its alphanumeric", Toast.LENGTH_LONG).show();
            focusView = confirmPassword;
            cancel = true;
        }

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

                try {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("new_password", nPassword);
                    map.put("current_password", oPassword);
                    map.put("type", "old");

                    restService.changePassword(map).enqueue(new Callback<ErrorResponse>() {
                        @Override
                        public void onResponse(Call<ErrorResponse> call, Response<ErrorResponse> response) {

                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }

                            if (response.body() != null && response.body().getStatus() == 200) {
                                GlobalData.showToast(getBaseContext(), "Password changed successfully", Toast.LENGTH_SHORT).show();
                                finish();
                                ChangePasswordActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                        R.anim.animation_f_leave);
                            } else if (response.body() != null && response.body().getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            } else if (response.body() != null) {
                                GlobalData.showToast(getBaseContext(), response.body().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();
                                if (message.getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    finish();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ErrorResponse> 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();
            }
        }
    }

    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(ChangePasswordActivity.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();
        }
    }
    protected void onResume() {
        super.onResume();

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

