package com.cpm.lorealbaautomation.password;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.DealarBoardActivity;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity;
import com.cpm.lorealbaautomation.dailyactivity.TabLoginActivity;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter;
import com.cpm.lorealbaautomation.pinviewactivity.PinViewActivity;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ChangePasswordActivity extends AppCompatActivity implements View.OnClickListener {
    String user_id, PASSWORD_CHANGE = "", activity_name = "", new_pw, old_password, visit_date, counterId;
    EditText et_old_password, et_new_password, et_confirm_password;
    ArrayList<LoginGetterSetter> allLoginData = new ArrayList<>();
    Button btn_submit;
    ImageView img_info;
    private SharedPreferences preferences = null;
    private SharedPreferences.Editor editor = null;
    boolean clicked_flag = false;
    ProgressDialog loading;
    Lorealba_Database db;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        context = this;
        db = new Lorealba_Database(context);
        db.open();

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        et_old_password = (EditText) findViewById(R.id.et_old_password);
        et_new_password = (EditText) findViewById(R.id.et_new_password);
        et_confirm_password = (EditText) findViewById(R.id.et_confirm_password);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        img_info = (ImageView) findViewById(R.id.img_info);
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        user_id = preferences.getString(CommonString.KEY_USERNAME, "");
        old_password = preferences.getString(CommonString.KEY_PASSWORD, "");

        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");

        if (getIntent().getStringExtra(CommonString.KEY_PASSWORD_CHANGE) != null) {
            PASSWORD_CHANGE = getIntent().getStringExtra(CommonString.KEY_PASSWORD_CHANGE);
        }

        if (getIntent().getStringExtra(CommonString.KEY_ACTIVITY) != null) {
            activity_name = getIntent().getStringExtra(CommonString.KEY_ACTIVITY);
        }

        db.open();
        allLoginData = db.getlistAllData(visit_date, user_id);
        if (allLoginData.size() > 0) {
            old_password = allLoginData.get(0).getPassword();
        }

        setTitle("Change Password - " + user_id);
        //new password
        et_new_password.addTextChangedListener(new TextWatcher() {
            @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) {
                String result = s.toString().replaceAll(" ", "");
                clicked_flag = true;
                if (!s.toString().equals(result)) {
                    et_new_password.setText(result);
                    et_new_password.setSelection(result.length());
                    et_new_password.setError(getString(R.string.space_not_allowed_in_password));
                    et_new_password.requestFocus();
                    // alert the user
                }
            }
        });

        //confirm password
        et_confirm_password.addTextChangedListener(new TextWatcher() {
            @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) {
                String result = s.toString().replaceAll(" ", "");
                clicked_flag = true;
                if (!s.toString().equals(result)) {
                    et_confirm_password.setText(result);
                    et_confirm_password.setSelection(result.length());
                    et_confirm_password.setError(getString(R.string.space_not_allowed_in_password));
                    et_confirm_password.requestFocus();
                    // alert the user
                }
            }
        });


        img_info.setOnClickListener(this);
        btn_submit.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.img_info) {
            Dialog dialog = new Dialog(ChangePasswordActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.setContentView(R.layout.password_rule_dialog);
            dialog.show();

        } else if (v.getId() == R.id.btn_submit) {
            submit();
        }
    }

    void submit() {
        boolean cancel = false;
        View focusView = null;
        //Old Password
        String old_pw = et_old_password.getText().toString().trim();
        new_pw = et_new_password.getText().toString();
        Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?=.*\\d).+$");
        if (old_pw.equals("")) {
            et_old_password.setError(getString(R.string.error_field_required));
            focusView = et_old_password;
            cancel = true;
        } else if (!old_password.equals("") && !old_pw.equals(old_password)) {
            et_old_password.setError(getString(R.string.error_incorrect_password));
            focusView = et_old_password;
            cancel = true;
        } else if (new_pw.equals("")) {
            //New Password
            et_new_password.setError(getString(R.string.error_field_required));
            focusView = et_new_password;
            cancel = true;
        } else if (new_pw.length() >= 8 && new_pw.length() <= 10 && textPattern.matcher(new_pw).matches()) {
            //New Password
            String confirm_pw = et_confirm_password.getText().toString();
            if (confirm_pw.equals("")) {
                et_confirm_password.setError(getString(R.string.error_field_required));
                focusView = et_confirm_password;
                cancel = true;
            } else if (!confirm_pw.equals(new_pw)) {
                et_confirm_password.setError(getString(R.string.password_and_confirm_password_not_match));
                focusView = et_confirm_password;
                cancel = true;
            } else {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("UserId", user_id);
                    jsonObject.put("OldPassword", old_password);
                    jsonObject.put("NewPassword", new_pw);
                    AuthenticateTask(jsonObject.toString());
                } catch (JSONException e) {
                    e.fillInStackTrace();
                }
            }
        } else {
            et_new_password.setError(getString(R.string.invalid_password));
            focusView = et_new_password;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();

        }

    }


    public void AuthenticateTask(String jsondata) {
        try {
            loading = ProgressDialog.show(context, "Change Password", "Updating.......", false, true);
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsondata);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<ResponseBody> call = api.getChangePassword(jsonData);
            call.enqueue(new retrofit2.Callback<ResponseBody>() {
                @Override
                public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                    ResponseBody responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().string();
                            data = data.substring(1, data.length() - 1).replace("\\", "");
                            if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                loading.dismiss();
                                if (PASSWORD_CHANGE != null && !PASSWORD_CHANGE.equals("") && PASSWORD_CHANGE.equalsIgnoreCase("Change")) {
                                    if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("Start")) {
                                        Toast.makeText(context, getString(R.string.password_updated_successfully), Toast.LENGTH_LONG).show();
                                        editor.putString(CommonString.KEY_PASSWORD_CHANGE, "");
                                        editor.commit();

                                        Intent in = new Intent(getApplicationContext(), PinViewActivity.class);
                                        in.putExtra(CommonString.IS_PASSWORD_CHECK, false);
                                        in.putExtra(CommonString.KEY_USERNAME, user_id);
                                        startActivity(in);
                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                        finish();
                                    } else if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("PinView")) {
                                        Toast.makeText(context, getString(R.string.password_updated_successfully), Toast.LENGTH_LONG).show();
                                        editor.putString(CommonString.KEY_PASSWORD_CHANGE, "");
                                        editor.commit();
                                        if (allLoginData.size() > 0) {
                                            if (allLoginData.get(0).getImg().equals("")) {
                                                startActivity(new Intent(context, StoreImageActivity.class));
                                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                finish();
                                            } else {
                                                startActivity(new Intent(context, DealarBoardActivity.class));
                                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                finish();
                                            }
                                        }
                                    }
                                } else {
                                    db.open();
                                    if (db.ischeck_login_data(user_id.toLowerCase())) {
                                        db.open();
                                        db.deleteTableWithLogin(user_id.toLowerCase());
                                    }

                                    if (user_id.toLowerCase().equals(user_id.toLowerCase())) {
                                        editor.putString(CommonString.KEY_PASSWORD, "");
                                        editor.putString(CommonString.MPIN, null);
                                        editor.putString(CommonString.KEY_USERNAME, "");
                                        editor.commit();
                                    }

                                    startActivity(new Intent(context, TabLoginActivity.class));
                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                    loading.dismiss();
                                    showAlert(getString(R.string.password_updated_successfully), true);
                                }
                            } else {
                                loading.dismiss();
                                showAlert(data + ". Please Try Again", false);
                            }

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                        }

                    } else {
                        loading.dismiss();
                        AlertandMessages.showToastMsg(context, "Server Not Responding . Please Try Again ");
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });

        } catch (Exception e) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }


    public void showAlert(String str, final boolean flag_finish) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ChangePasswordActivity.this);
        builder.setTitle(R.string.dialog_title);
        builder.setMessage(str).setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if (flag_finish) {
                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                                ChangePasswordActivity.this.finish();
                            }
                        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ChangePasswordActivity.this.finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(
                                DialogInterface dialog, int id) {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            ChangePasswordActivity.this.finish();
                        }
                    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ChangePasswordActivity.this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loading != null && loading.isShowing()) {
            loading.dismiss();
        }
    }
}
