package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
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 ResetPasswordActivity 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;
  TextView mTitle;

  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(ResetPasswordActivity.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);
    mTitle=   findViewById(R.id.title);

    findViewById(R.id.continueButton).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        attemptLogin();
      }
    });
    mTitle.setText("RESET PASSWORD");
    Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
    backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
    ImageView imageView = findViewById(R.id.back_btn);
    imageView.setImageDrawable(backArrow);
    imageView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        finish();
        overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
      }
    });

//        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(), ForgotPasswordActivity.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(ResetPasswordActivity.this)) {
        progressDialog = new TransparentProgressDialog(ResetPasswordActivity.this);
        progressDialog.show();

        try {
          HashMap<String, String> map = new HashMap<>();
          map.put("new_password", nPassword);
          map.put("type", "change");
          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) {

                //  GlobalData.showToast(getBaseContext(), "Your password is created successfully", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(ResetPasswordActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
              } 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();
      }
    }
  }


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

}

