package com.tool.applockpro.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.anythink.core.api.AdError;
import com.anythink.interstitial.api.ATInterstitial;
import com.tool.applockpro.ApplockSkin;
import com.tool.applockpro.R;
import com.tool.applockpro.databinding.ActivitySetPwdactivityBinding;
import com.tool.applockpro.tool.Adcallback;
import com.tool.applockpro.tool.Mytools;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class SetPWDActivity extends AppCompatActivity {
    ActivitySetPwdactivityBinding binding;
    private List<EditText> etlis = new ArrayList<>();
    private int chewkpwd;
    private List<ATInterstitial> ads;
    private String firstPwd = "";
    private String secondPwd = "";

    private boolean showClose = false;

    public static String KEY_SHOW_CLOSE = "KEY_CLOSE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showClose = getIntent().getBooleanExtra(KEY_SHOW_CLOSE, showClose);
        binding = ActivitySetPwdactivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        if(showClose){
            binding.close.setVisibility(View.VISIBLE);

        }else {
            binding.close.setVisibility(View.GONE);
        }
        binding.close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_setpwd), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ads = ApplockSkin.lodAd();
        chewkpwd = getIntent().getIntExtra("1", 0);
        etlis.add(binding.et1);
        etlis.add(binding.et2);
        etlis.add(binding.et3);
        etlis.add(binding.et4);
        setupEditTextListeners();
        initEvent();
    }

    private void showAd() {
        ATInterstitial mInterstitialAd = Mytools.onCache(ads);
        if (mInterstitialAd == null) {
            finish();
        } else {
            Mytools.setCallback(mInterstitialAd, new Adcallback() {
                @Override
                public void onShowFail(AdError ad) {
                    finish();
                }

                @Override
                public void onAdHidden() {
                    finish();
                }
            });
            mInterstitialAd.show(this);
        }

    }

    private void initEvent() {

        binding.btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(binding.et1.getText().toString());
                stringBuilder.append(binding.et2.getText().toString());
                stringBuilder.append(binding.et3.getText().toString());
                stringBuilder.append(binding.et4.getText().toString());
                if (stringBuilder.length() == 4) {
                    if (TextUtils.isEmpty(firstPwd)) {
                        firstPwd = stringBuilder.toString();

                        Log.e("zzj", "---first set pwd---" + stringBuilder.toString());

                        Log.e("zzj", "---clear stringBuilder---" + stringBuilder.toString());
                        binding.et1.setText("");
                        binding.et2.setText("");
                        binding.et3.setText("");
                        binding.et4.setText("");
                        binding.et1.requestFocus();

                        binding.lockText1.setText(R.string.lock_re_enter);

                    } else {

                        stringBuilder.setLength(0);
                        stringBuilder.append(binding.et1.getText().toString());
                        stringBuilder.append(binding.et2.getText().toString());
                        stringBuilder.append(binding.et3.getText().toString());
                        stringBuilder.append(binding.et4.getText().toString());
                        Log.e("zzj", "---set stringBuilder---" + stringBuilder.toString());
                        secondPwd = stringBuilder.toString();
                        Log.e("zzj", "---get firstPwd---" + firstPwd);
                        if (secondPwd.equals(firstPwd)) {
                            ApplockSkin.savePWD(secondPwd);
                            Log.e("zzj", "---second set pwd---" + stringBuilder.toString());
                            if (chewkpwd == ApplockSkin.checkpwd_0) {
                                Intent intent = new Intent(SetPWDActivity.this, MainActivity.class);
                                Toast.makeText(SetPWDActivity.this, getString(R.string.setlock_tips), Toast.LENGTH_SHORT).show();
                                startActivity(intent);
                                finish();

                            } else {

                                Toast.makeText(SetPWDActivity.this, getString(R.string.changelock_tips), Toast.LENGTH_SHORT).show();
                                showAd();
                            }
                        }
                    }
                    updateEditTextBackgrounds();

                } else {
                    Toast.makeText(SetPWDActivity.this, getString(R.string.text_hint), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void updateEditTextBackgrounds() {
        Log.d(ApplockSkin.TAG,"------updateEditTextBackgrounds");
        for (EditText editText : etlis) {
            if (!TextUtils.isEmpty(editText.getText())) {
                editText.setSelected(true);
            } else {
                editText.setSelected(false);
            }
        }
    }

    private void setupEditTextListeners() {
        for (int i = 0; i < etlis.size(); i++) {
            EditText currentEditText = etlis.get(i);
            EditText nextEditText = (i < etlis.size() - 1) ? etlis.get(i + 1) : null;
            EditText previousEditText = (i > 0) ? etlis.get(i - 1) : null;
            int finalI = i;
            currentEditText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    Log.d(ApplockSkin.TAG,"------s="+s.toString());
                    if(s.toString().isEmpty()){
                        currentEditText.setSelected(false);
                    }else {
                        currentEditText.setSelected(true);
                    }

                    if (s.length() == 1 && nextEditText != null) {
                        nextEditText.requestFocus();
                    } else if (s.length() == 0 && previousEditText != null) {
                        previousEditText.requestFocus();
                    } else if (finalI == 3 || finalI == 0) {

                        currentEditText.clearFocus();
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(currentEditText.getWindowToken(), 0);
                    }
                }
            });

        }
    }
}