package kr.co.icontrols.iotplatform;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler;

import kr.co.icontrols.iotplatform.cognito.AppHelper;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.isPasswordValid;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.setupUI;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;

public class ChangePasswordActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher{

    private EditText txtPassword, txtNewPassword, txtComfirmPassword;

    private AlertDialog userDialog;
    private ProgressDialog waitDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);

        setupUI(this,findViewById(R.id.layoutMain));

        txtPassword = findViewById(R.id.txtPassword);
        txtNewPassword = findViewById(R.id.txtNewPassword);
        txtComfirmPassword = findViewById(R.id.txtComfirmPassword);

        txtPassword.addTextChangedListener(this);
        txtNewPassword.addTextChangedListener(this);
        txtComfirmPassword.addTextChangedListener(this);
    }

    @Override
    protected void onPause() {
        ForceDismissConnectDialog();
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        /*
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);
        */

        switch (v.getId()) {
            case R.id.btnBack:
            case R.id.btnBackText:
                onBackPressed();
                break;
            case R.id.btnRight:
            case R.id.btnOk:
                if(txtPassword == null || txtPassword.getText().toString().isEmpty()) {
                    Toast.makeText(this,"현재 비밀번호 없음",Toast.LENGTH_SHORT).show();
                } else if(txtNewPassword == null || txtNewPassword.getText().toString().isEmpty()) {
                    Toast.makeText(this,"새로운 비밀번호 없음",Toast.LENGTH_SHORT).show();
                } else if(txtComfirmPassword == null || txtComfirmPassword.getText().toString().isEmpty()) {
                    Toast.makeText(this,getString(R.string.input_password_comfirm),Toast.LENGTH_SHORT).show();
                } else if(!(txtNewPassword.getText().toString().equals(txtComfirmPassword.getText().toString()))) {
                    Toast.makeText(this,getString(R.string.not_same_password),Toast.LENGTH_SHORT).show();
                } else if(!isPasswordValid(txtPassword.getText().toString())) {
                    Toast.makeText(this,getString(R.string.invalid_password),Toast.LENGTH_SHORT).show();
                } else {
                    String cPass = txtPassword.getText().toString();
                    String nPass = txtNewPassword.getText().toString();
                    displayProgress(ChangePasswordActivity.this,"","");//showWaitDialog("Changing password...");
                    AppHelper.getPool().getUser(AppHelper.getCurrUser()).changePasswordInBackground(cPass, nPass, callback);
                }
                break;
        }
    }

    GenericHandler callback = new GenericHandler() {
        @Override
        public void onSuccess() {
            DismissConnectDialog();//closeWaitDialog();
            //showDialogMessage("Success!","Password has been changed",true);
            showNotiMsg(ChangePasswordActivity.this,"Your password was changed");
            clearInput();
        }

        @Override
        public void onFailure(Exception exception) {
            DismissConnectDialog();//closeWaitDialog();
            showDialogMessage("Password change failed", AppHelper.formatException(exception), false);
        }
    };

    private  void clearInput() {
        txtPassword.setText("");
        txtNewPassword.setText("");
        txtComfirmPassword.setText("");
    }

    private void showDialogMessage(String title, String body, final boolean exitActivity) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title).setMessage(body).setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    userDialog.dismiss();
                    if (exitActivity) {
                        onBackPressed();
                    }
                } catch (Exception e) {
                    onBackPressed();
                }
            }
        });
        userDialog = builder.create();
        userDialog.show();
    }

    private void showWaitDialog(String message) {
        closeWaitDialog();
        waitDialog = new ProgressDialog(this);
        waitDialog.setTitle(message);
        waitDialog.show();
    }

    private void closeWaitDialog() {
        try {
            waitDialog.dismiss();
        }
        catch (Exception e) {
            // Wait dialog is already closed or does not exist
        }
    }

    @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) {
        if(txtComfirmPassword.length() > 0 && txtNewPassword.length() > 0 && txtPassword.length() > 0) {
            findViewById(R.id.btnBack).setVisibility(View.GONE);
            findViewById(R.id.btnBackText).setVisibility(View.VISIBLE);
            findViewById(R.id.btnRight).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.btnBack).setVisibility(View.VISIBLE);
            findViewById(R.id.btnBackText).setVisibility(View.GONE);
            findViewById(R.id.btnRight).setVisibility(View.INVISIBLE);
        }
    }
}