package com.cygnusa.hyperm.screenpinview;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
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.cygnusa.hyperm.MyWallet;
import com.cygnusa.hyperm.OtpActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.screenpinview.enums.KeyboardButtonEnum;
import com.cygnusa.hyperm.screenpinview.interfaces.KeyboardButtonClickedListener;
import com.cygnusa.hyperm.screenpinview.views.KeyboardView;
import com.cygnusa.hyperm.screenpinview.views.PinCodeRoundView;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
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 java.util.HashMap;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Response;

public class AppLockActivity extends AppCompatActivity
        implements KeyboardButtonClickedListener {

    private int DEFAULT_PIN_LENGTH = 4;
    protected TextView mStepTextView;
    protected TextView mForgotTextView;
    protected PinCodeRoundView mPinCodeRoundView;
    protected KeyboardView mKeyboardView;
    AlertDialog.Builder alertDialogBuilder;
    AlertDialog alertDialog;
    protected String mPinCode;
    protected String mOldPinCode;

    TransparentProgressDialog progressDialog;
    ApiService restService;
    boolean isCalled = false;
    public 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("Wallet PIN");

        mStepTextView = findViewById(R.id.pin_code_step_textview);
        mPinCodeRoundView = findViewById(R.id.pin_code_round_view);
        mPinCodeRoundView.setPinLength(DEFAULT_PIN_LENGTH);
        mForgotTextView = findViewById(R.id.pin_code_forgot_textview);
        SpannableString loginText = new SpannableString("Forgot MPIN?");
        loginText.setSpan(new UnderlineSpan(), 0, loginText.length(), 0);
        mForgotTextView.setText(loginText);
        mForgotTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(AppLockActivity.this, OtpActivity.class);
                i.putExtra("type", "forgot");
                startActivity(i);
                finish();
            }
        });
        mKeyboardView = this.findViewById(R.id.pin_code_keyboard_view);
        mKeyboardView.setKeyboardButtonClickedListener(this);

        if (GlobalData.user.getData().getMpin().trim().isEmpty()) {
            mStepTextView.setText("Create 4 Digit PIN");
        } else {
            mStepTextView.setText("Enter 4 digit 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);
            }
            Log.e("value ", value + " lenthxx " + mPinCode.length() + "mpin value" + mPinCode.toString());
        }
    }

    @Override
    public void onRippleAnimationEnd() {
        Log.e("dddout", mPinCode.length() + "codeout" + mPinCode.toString() + "");
        if (mPinCode.length() == DEFAULT_PIN_LENGTH) {
            Log.e("dddout1", mPinCode.length() + "code" + mPinCode.toString() + "");
            if (!isCalled) {
                isCalled = true;
                onPinCodeInputed();
            }

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

    @SuppressLint("SetTextI18n")
    protected void onPinCodeInputed() {
        if (GlobalData.user.getData().getMpin().trim().isEmpty()) {
            if (mOldPinCode.isEmpty()) {
                mOldPinCode = mPinCode;
                mPinCode = "";
                mPinCodeRoundView.refresh(mPinCode.length());
                mStepTextView.setText("Confirm 4 digit PIN");
            } else if (mOldPinCode.equalsIgnoreCase(mPinCode)) {
                postMPIN(mPinCode);
            } else {
                onPinCodeError();
            }
        } else if (GlobalData.user.getData().getMpin().trim().equalsIgnoreCase(mPinCode)) {
            startActivity(new Intent(AppLockActivity.this, MyWallet.class));
            finish();
        } else {
            onPinCodeError();
        }
    }

    @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(
                        AppLockActivity.this, R.anim.shake);
                mKeyboardView.startAnimation(animation);

                if (GlobalData.user.getData().getMpin().trim().isEmpty()) {
                    mStepTextView.setText("Create 4 digit PIN");
                } else {
                    mStepTextView.setText("Enter 4 digit PIN");
                }
            }
        };
        runOnUiThread(thread);
    }

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

    private void postMPIN(String mpin) {
        if (new UtilService().isNetworkAvailable(AppLockActivity.this)) {
            progressDialog = new TransparentProgressDialog(AppLockActivity.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 created 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);
                            startActivity(new Intent(AppLockActivity.this, MyWallet.class));
                            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();
        }
    }
}
