package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;

import java.util.HashMap;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SetNewPasswordActivity extends AppCompatActivity {
    EditText newPassword, confirmPassword;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    // String PASSWORD_PATTERN = "((?=.*[a-zA-Z0-9]).{8,32})";
    String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z,A-Z]).{8,30})";
    AlertDialog.Builder alertDialogBuilder;
    AlertDialog alertDialog;
    String userName;
    public  static String accessToken;

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_set_password);
        GlobalData.openDatabase(SetNewPasswordActivity.this);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            userName = extras.getString("username");

        }

        restService = ((MainApplication) getApplication()).getClient();
        newPassword = findViewById(R.id.newPassword);
        confirmPassword = findViewById(R.id.confirmPassword);


        findViewById(R.id.continueButton).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

//        Toolbar toolbar = findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        toolbar.setTitle("");
//        getSupportActionBar().setTitle("");
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            startActivity(new Intent(getBaseContext(), LoginActivity.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(getBaseContext(), SignUpActivity.class));
        finish();
    }

    private void attemptLogin() {
        String nPassword = newPassword.getText().toString().trim();
        String cPassword = confirmPassword.getText().toString().trim();
        if (TextUtils.isEmpty(nPassword) && TextUtils.isEmpty(cPassword)) {
            GlobalData.showToast(getBaseContext(), "Please fill in all necessary fields.", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(nPassword)) {
            GlobalData.showToast(getBaseContext(), "Please enter the new password", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(cPassword)) {
            GlobalData.showToast(getBaseContext(), "Please enter the confirm password", Toast.LENGTH_SHORT).show();
        } else if (!nPassword.equals(cPassword)) {
            GlobalData.showToast(getBaseContext(), "The entered passwords does not match", Toast.LENGTH_SHORT).show();
        } else if (!Pattern.compile(PASSWORD_PATTERN).matcher(cPassword).matches()) {
            GlobalData.showToast(getBaseContext(), "The password must have at least 8 characters, " +
                    " and its alphanumeric." +
                    "", Toast.LENGTH_LONG).show();
        } else {
            if (new UtilService().isNetworkAvailable(SetNewPasswordActivity.this)) {
                progressDialog = new TransparentProgressDialog(SetNewPasswordActivity.this);
                progressDialog.show();

                try {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("new_password", nPassword);
                    map.put("type", "register");
                    map.put("username", userName);
                    restService.changePassword(map).enqueue(new Callback<ErrorResponse>() {
                        @Override
                        public void onResponse(Call<ErrorResponse> call, Response<ErrorResponse> response) {

                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }

                            if (response.body() != null && response.body().getStatus() == 200) {
                                ((MainApplication) getApplication()).addAccessToken(String.format("Bearer %s", response.body().getAccess_token()));
                                accessToken=response.body().getAccess_token();
                                restService = ((MainApplication) getApplication()).getClient();
                                //  GlobalData.showToast(getBaseContext(), "Your password is created successfully", Toast.LENGTH_SHORT).show();
                                showInstructions();
                            } else if (response.body() != null) {
                                GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            } else if (response.errorBody() != null) {
                                Gson gson = new Gson();
                                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @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();
            }
        }
    }

    private void showInstructions() {
        View view = LayoutInflater.from(SetNewPasswordActivity.this).inflate(
                R.layout.signup_instruction_popup, null);
        TextView textHead = (TextView) view.findViewById(R.id.textHead);
        TextView text1 = (TextView) view.findViewById(R.id.text1);
        TextView text2 = (TextView) view.findViewById(R.id.text2);
        TextView text3 = (TextView) view.findViewById(R.id.text3);
        TextView text4 = (TextView) view.findViewById(R.id.text4);
        text2.setVisibility(View.INVISIBLE);
        text3.setVisibility(View.INVISIBLE);
        text4.setVisibility(View.INVISIBLE);
        textHead.setText("Fill in the mandatory fields");
        text1.setText("You are one step closer to complete the registration");
        text1.setGravity(Gravity.CENTER);
        view.findViewById(R.id.btn_ok).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        startActivity(new Intent(getBaseContext(), MainProfileActivity.class));
                        finish();
                    }
                });

        alertDialogBuilder = new AlertDialog.Builder(SetNewPasswordActivity.this);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setView(view);
        alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(SetNewPasswordActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

