package kr.co.icontrols.iotplatform;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserAttributes;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.SignUpHandler;
import com.amazonaws.services.cognitoidentityprovider.model.CodeDeliveryDetailsType;
import com.amazonaws.services.cognitoidentityprovider.model.SignUpResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import kr.co.icontrols.iotplatform.DataClass.KakaoLocationInfo;
import kr.co.icontrols.iotplatform.cognito.AppHelper;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
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;
import static kr.co.icontrols.iotplatform.utils.Constants.COGNITO_NICKNAME;
import static kr.co.icontrols.iotplatform.utils.Constants.COGNITO_PHONENUMBER;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class SignUpInputActivity extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "SignUpInputActivity";

    private EditText txtId, txtPassword, txtComfirmPassword, txtNickName, txtHp;

    private AlertDialog userDialog;
    private ProgressDialog waitDialog;
    private String usernameInput;
    private String userpasswdInput;
    private String userNickName;
    private String userHp;

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

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

        txtId = findViewById(R.id.txtId);
        txtPassword = findViewById(R.id.txtPassword);
        txtComfirmPassword = findViewById(R.id.txtComfirmPassword);
        txtNickName = findViewById(R.id.txtNickName);
        txtHp = findViewById(R.id.txtHp);
    }

    @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(!((CheckBox)findViewById(R.id.chkAgreeService)).isChecked()) {
                    showNotiMsg(this, "약관 동의 후 가능합니다.");
                } else if(txtId == null || txtId.getText().toString().isEmpty()) {
                    showNotiMsg(this,getString(R.string.input_id));
                } else if(txtPassword == null || txtPassword.getText().toString().isEmpty()) {
                    showNotiMsg(this,getString(R.string.input_password));
                } else if(txtComfirmPassword == null || txtComfirmPassword.getText().toString().isEmpty()) {
                    showNotiMsg(this,getString(R.string.input_password_comfirm));
                } else if(!(txtPassword.getText().toString().equals(txtComfirmPassword.getText().toString()))) {
                    showNotiMsg(this,getString(R.string.not_same_password));
                } else if(!isPasswordValid(txtPassword.getText().toString())) {
                    showNotiMsg(this,getString(R.string.invalid_password));
                } else if(txtNickName == null || txtNickName.getText().toString().isEmpty()) {
                    showNotiMsg(this,getString(R.string.input_nickname));
                } else if(txtNickName == null || txtNickName.getText().toString().length() < 4) {
                    showNotiMsg(this,getString(R.string.short_nickname));
                } else if(txtHp == null || txtHp.getText().toString().isEmpty()) {
                    showNotiMsg(this,getString(R.string.input_phone_number));
                } else {
                    usernameInput = txtId.getText().toString();
                    userpasswdInput = txtPassword.getText().toString();
                    userNickName = txtNickName.getText().toString();
                    userHp = txtHp.getText().toString();

                    try {
                        displayProgress(SignUpInputActivity.this,"","");
                        HttpApi.isValidateUserInfo(usernameInput, userNickName, userHp, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                e.printStackTrace();
                                ErrorLogOutput(TAG, "HttpApi.isValidateUserInfo(onFailure)\n" + e.toString());
                                DismissConnectDialog();
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                if(response.code() == HTTP_OK) {
                                    WarnLogOutput(TAG, "HttpApi.isValidateUserInfo(onResponse) : HTTP_OK");
                                    try {
                                        JSONObject json_data = new JSONObject(response.body().string());
                                        WarnLogOutput(TAG, "body : "+json_data.toString());

                                        final String email = json_data.isNull("email") ? "" : json_data.getString("email");
                                        final String nickname = json_data.isNull("nickname") ? "" : json_data.getString("nickname");
                                        final String phoneNumber = json_data.isNull("phoneNumber") ? "" : json_data.getString("phoneNumber");

                                        if(email.equals("VALID") && nickname.equals("VALID") && phoneNumber.equals("VALID")) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    CognitoUserAttributes userAttributes = new CognitoUserAttributes();
                                                    userAttributes.addAttribute(AppHelper.getSignUpFieldsC2O().get(COGNITO_NICKNAME).toString(), txtNickName.getText().toString());
                                                    userAttributes.addAttribute(AppHelper.getSignUpFieldsC2O().get(COGNITO_PHONENUMBER).toString(), "+82"+txtHp.getText().toString().substring(1));

                                                    //showWaitDialog("Signing up...");
                                                    AppHelper.getPool().signUpInBackground(usernameInput, userpasswdInput, userAttributes, null, signUpHandler);
                                                }
                                            });
                                        } else {
                                            //UI 업데이트
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String msg = "";
                                                    if(email.equals("EXIST")) {
                                                        msg = (msg.isEmpty()?"":"\n")+"이메일이 존재합니다.";
                                                    } else if(email.equals("INVALID")) {
                                                        msg = (msg.isEmpty()?"":"\n")+"이메일이 유효하지 않습니다.";
                                                    } else if(nickname.equals("EXIST")) {
                                                        msg = (msg.isEmpty()?"":"\n")+"별명이 존재합니다. ";
                                                    } else if(nickname.equals("INVALID")) {
                                                        msg = (msg.isEmpty()?"":"\n")+"별명이 유효하지 않습니다.";
                                                    } else if(phoneNumber.equals("EXIST")) {
                                                        msg = (msg.isEmpty()?"":"\n")+"휴대포번호가 존재합니다.";
                                                    } else if(phoneNumber.equals("INVALID")) {
                                                        msg = (msg.isEmpty()?"":"\n")+"휴대포번호가 존재합니다.";
                                                    }
                                                   showNotiMsg(SignUpInputActivity.this, msg);
                                                   DismissConnectDialog();
                                                }
                                            });
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                        ErrorLogOutput(TAG, "HttpApi.isValidateUserInfo(JSONException)\n" + e.toString());
                                        DismissConnectDialog();
                                    }
                                } else {
                                    ErrorLogOutput(TAG, "HttpApi.isValidateUserInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                    DismissConnectDialog();
                                    try {
                                        JSONObject json_data = new JSONObject(response.body().string());
                                        ErrorLogOutput(TAG, "HttpApi.isValidateUserInfo(onResponse) body : " + json_data.toString());
                                    } catch (JSONException e) {
                                        ErrorLogOutput(TAG, "HttpApi.isValidateUserInfo(onResponse) JSONException : " + e.toString());
                                    }
                                }
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                        ErrorLogOutput(TAG, "HttpApi.isValidateUserInfo(IOException)\n" + e.toString());
                        DismissConnectDialog();
                    }
                }

                //startActivity(new Intent(this, SignUpCertificationActivity.class));
                break;
            case R.id.btnShowDetail:
                startActivity(new Intent(this, PrivacyPolicyActivity.class));
                break;
        }
    }

    SignUpHandler signUpHandler = new SignUpHandler() {
        @Override
        public void onSuccess(CognitoUser user, SignUpResult signUpResult) {
            // Check signUpConfirmationState to see if the user is already confirmed
            DismissConnectDialog();//closeWaitDialog();
            Boolean regState = signUpResult.getUserConfirmed();
            if (regState) {
                // User is already confirmed
                //showDialogMessage("Sign up successful!",usernameInput+" has been Confirmed", true);
                //showNotiMsg(SignUpInputActivity.this,"회원가입을 완료하였습니다.");
                startActivity(new Intent(SignUpInputActivity.this,SignUpFinishActivity.class));
                finish();
            }
            else {
                // User is not confirmed
                confirmSignUp(signUpResult.getCodeDeliveryDetails());
            }
        }

        @Override
        public void onFailure(Exception exception) {
            DismissConnectDialog();//closeWaitDialog();
//            TextView label = (TextView) findViewById(R.id.textViewRegUserIdMessage);
//            label.setText("Sign up failed");
//            username.setBackground(getDrawable(R.drawable.text_border_error));
            //showDialogMessage("Sign up failed",AppHelper.formatException(exception),false);
            showNotiMsg(SignUpInputActivity.this,"회원가입을 실패하였습니다.");
        }
    };

    private void confirmSignUp(CodeDeliveryDetailsType cognitoUserCodeDeliveryDetails) {
        Intent intent = new Intent(this, SignUpCertificationActivity.class);
        intent.putExtra("source","signup");
        intent.putExtra("name", usernameInput);
        intent.putExtra("destination", cognitoUserCodeDeliveryDetails.getDestination());
        intent.putExtra("deliveryMed", cognitoUserCodeDeliveryDetails.getDeliveryMedium());
        intent.putExtra("attribute", cognitoUserCodeDeliveryDetails.getAttributeName());
        startActivityForResult(intent, 10);
    }

    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(usernameInput);
                    }
                } catch (Exception e) {
                    if(exit) {
                        exit(usernameInput);
                    }
                }
            }
        });
        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) {
            //
        }
    }

    private void exit(String uname) {
        exit(uname, null);
    }

    private void exit(String uname, String password) {
        Intent intent = new Intent();
        if (uname == null) {
            uname = "";
        }
        if (password == null) {
            password = "";
        }
        intent.putExtra("name", uname);
        intent.putExtra("password", password);
        setResult(RESULT_OK, intent);
        finish();
    }
}