package kr.co.icontrols.iotplatform;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserAttributes;

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

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 NewPasswordActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText txtPassword, txtComfirmPassword;
    private AlertDialog userDialog;

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

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

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

        refreshItemsDisplayed();
    }

    @Override
    public void onBackPressed() {
        exit(false);
    }

    @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:
                onBackPressed();
                break;
            case R.id.btnOk:
                if(txtPassword == null || txtPassword.getText().toString().isEmpty()) {
                    Toast.makeText(this,getString(R.string.input_password),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(!(txtPassword.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 newUserPassword = txtPassword.getText().toString();
                    if (newUserPassword != null) {
                        AppHelper.setPasswordForFirstTimeLogin(newUserPassword);
                        if (checkAttributes()) {
                            exit(true);
                        }
                    }
                    showNotiMsg(NewPasswordActivity.this, "비밀번호 변경 중 오류가 발생하였습니다."); //showDialogMessage("Error", "Enter all required attributed", false);
                }
                break;
        }
    }

    private void refreshItemsDisplayed() {
        final FirstTimeLoginAttributesDisplayAdapter attributesAdapter =
                new FirstTimeLoginAttributesDisplayAdapter(getApplicationContext());
        final ListView displayListView;
        displayListView = (ListView) findViewById(R.id.listViewCurrentUserDetails);
        displayListView.setAdapter(attributesAdapter);
        displayListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView data = (TextView) view.findViewById(R.id.editTextUserDetailInput);
                String attributeType = data.getHint().toString();
                String attributeValue = data.getText().toString();
                showAttributeDetail(attributeType, attributeValue);
            }
        });
    }

    private void showAttributeDetail(final String attributeType, final String attributeValue) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(attributeType);
        final EditText input = new EditText(NewPasswordActivity.this);
        input.setText(attributeValue);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        input.setLayoutParams(lp);
        input.requestFocus();
        builder.setView(input);

        builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    String newValue = input.getText().toString();
                    if (!newValue.equals(attributeValue)) {
                        AppHelper.setUserAttributeForFirstTimeLogin(attributeType, newValue);
                        refreshItemsDisplayed();
                    }
                    userDialog.dismiss();
                } catch (Exception e) {
                    // Log failure
                }
            }
        });
        userDialog = builder.create();
        userDialog.show();
    }

    private boolean checkAttributes() {
        // Check if all required attributes have values
        return true;
    }

    private void showDialogMessage(String title, String body, final boolean exit) {
        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 (exit) {
                        exit(false);
                    }
                } catch (Exception e) {
                    exit(false);
                }
            }
        });
        userDialog = builder.create();
        userDialog.show();
    }

    private void exit(Boolean continueWithSignIn) {
        Intent intent = new Intent();
        intent.putExtra("continueSignIn", continueWithSignIn);
        setResult(RESULT_OK, intent);
        finish();
    }
}