package com.ttiglobal.inttilectgpchat.screenpinview;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.screenpinview.enums.KeyboardButtonEnum;
import com.ttiglobal.inttilectgpchat.screenpinview.interfaces.KeyboardButtonClickedListener;
import com.ttiglobal.inttilectgpchat.screenpinview.views.KeyboardView;
import com.ttiglobal.inttilectgpchat.screenpinview.views.PinCodeRoundView;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.MyCallback;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.util.UtilService;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;
import com.ttiglobal.inttilectgpchat.wrappers.UserResponse;

import java.util.HashMap;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Response;

public class ChangeAppLockActivity extends AppCompatActivity
        implements KeyboardButtonClickedListener {

    private int DEFAULT_PIN_LENGTH = 4;
    protected TextView mStepTextView,mForgotView;
    protected PinCodeRoundView mPinCodeRoundView;
    protected KeyboardView mKeyboardView;
    protected String mPinCode;
    protected String mOldPinCode;

    TransparentProgressDialog progressDialog;
    ApiService restService;
    boolean isCalled = false;
    private TextView mTitle;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pin_code);
        overridePendingTransition(R.anim.nothing, R.anim.nothing);
        restService = ((MainApplication) getApplication()).getClient();

        mPinCode = "";
        mOldPinCode = "";

        mTitle = findViewById(R.id.title);
        mTitle.setText("Change Wallet PIN");
        mStepTextView = findViewById(R.id.pin_code_step_textview);
        mPinCodeRoundView = findViewById(R.id.pin_code_round_view);
        mForgotView = findViewById(R.id.pin_code_forgot_textview);
        mForgotView.setVisibility(View.GONE);
        mPinCodeRoundView.setPinLength(DEFAULT_PIN_LENGTH);

        mKeyboardView = this.findViewById(R.id.pin_code_keyboard_view);
        mKeyboardView.setKeyboardButtonClickedListener(this);

        mStepTextView.setText("Enter Current PIN");
    }


    @Override
    public void onKeyboardClick(KeyboardButtonEnum keyboardButtonEnum) {
        if (mPinCode.length() < DEFAULT_PIN_LENGTH) {
            int value = keyboardButtonEnum.getButtonValue();

            if (value == KeyboardButtonEnum.BUTTON_CLEAR.getButtonValue()) {
                if (!mPinCode.isEmpty()) {
                    setPinCode(mPinCode.substring(0, mPinCode.length() - 1));
                } else {
                    setPinCode("");
                }
            } else {
                setPinCode(mPinCode + value);
            }
        }
    }

    @Override
    public void onRippleAnimationEnd() {
        if (mPinCode.length() == DEFAULT_PIN_LENGTH) {
            if (!isCalled) {
                isCalled = true;
                onPinCodeInputed();
            }

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isCalled = false;
                }
            }, 500);
        }
    }

    @SuppressLint("SetTextI18n")
    protected void onPinCodeInputed() {
        switch (mStepTextView.getText().toString().trim()) {
            case "Enter Current PIN":
                if (GlobalData.user.getData().getMpin().trim().equalsIgnoreCase(mPinCode)) {
                    mPinCode = "";
                    mPinCodeRoundView.refresh(mPinCode.length());
                    mStepTextView.setText("Enter 4 digit PIN");
                } else {
                    onPinCodeError();
                }
                break;
            case "Enter 4 digit PIN":
                mOldPinCode = mPinCode;
                mPinCode = "";
                mPinCodeRoundView.refresh(mPinCode.length());
                mStepTextView.setText("Confirm 4 digit PIN");
                break;
            default:
                if (mOldPinCode.equalsIgnoreCase(mPinCode)) {
                    postMPIN(mPinCode);
                } else {
                    onPinCodeError();
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.nothing, R.anim.slide_down);
    }

    protected void onPinCodeError() {
        Thread thread = new Thread() {
            @SuppressLint("SetTextI18n")
            public void run() {
                mPinCode = "";
                mOldPinCode = "";
                mPinCodeRoundView.refresh(mPinCode.length());
                Animation animation = AnimationUtils.loadAnimation(
                        ChangeAppLockActivity.this, R.anim.shake);
                mKeyboardView.startAnimation(animation);
                mStepTextView.setText("Enter Current PIN");
            }
        };
        runOnUiThread(thread);
    }

    public void setPinCode(String pinCode) {
        mPinCode = pinCode;
        mPinCodeRoundView.refresh(mPinCode.length());
    }

    private void postMPIN(String mpin) {
        if (new UtilService().isNetworkAvailable(ChangeAppLockActivity.this)) {
            progressDialog = new TransparentProgressDialog(ChangeAppLockActivity.this);
            progressDialog.show();

            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("mpin", mpin);

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

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

                        if (response.body() != null && Objects.requireNonNull(response.body()).getStatus() == 200) {
                            GlobalData.showToast(getBaseContext(), "MPIN updated successfully", Toast.LENGTH_SHORT).show();
                            GlobalData.user.getData().setMpin(ids);
                            GlobalData.sdb.delete("session", null, null);
                            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);
                            finish();
                        } else if (response.body() != null && Objects.requireNonNull(response.body()).getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(getBaseContext(), Objects.requireNonNull(response.body()).getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(Objects.requireNonNull(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();
        }
    }
    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }
}
