package com.cpm.lorealbaautomation.forgotpassword;

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.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.appcompat.widget.Toolbar;

import android.text.InputFilter;
import android.text.Spanned;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.goodiebag.pinview.Pinview;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
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.constant.RoundedImageView;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

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

import java.io.File;
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;

import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

public class ForgotpasswordActity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private String visit_date, counterId, user_type, otp_code = "", str_user_name = "", user_id;
    ArrayList<BaListGetterSetter> bsListData = new ArrayList<>();
    private SharedPreferences.Editor editor = null;
    SharedPreferences preferences;
    private Lorealba_Database db;
    ProgressDialog loading;
    Toolbar toolbar;
    Context context;

    EditText edt_password, edt_confirm_password;
    CardView card_forgot_password_layout, card_view_forgot_password_top;
    FloatingActionButton btn_save_forgot;
    RoundedImageView round_img_pic;
    LinearLayout rl_otp_pinview;
    TextView forgot_user_name, profile_user, profile_user_type, txt_confirm_pin;
    ImageView img_invisible, img_info;
    ArrayAdapter<CharSequence> user_adapter;
    Spinner user_spin;
    boolean clicked_flag = false;
    Pinview pinview_otp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgotpassword_actity);
        context = this;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();
        getId();
        set_user_icon();
        setpin_view();
    }

    private void getId() {
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        user_type = preferences.getString(CommonString.KEY_USER_TYPE, "");
        user_id = preferences.getString(CommonString.KEY_USERNAME, "");
        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);
        }

        pinview_otp = (Pinview) findViewById(R.id.pinview_otp);
        img_invisible = (ImageView) findViewById(R.id.img_invisible);
        img_info = (ImageView) findViewById(R.id.img_info);
        forgot_user_name = (TextView) findViewById(R.id.forgot_user_name);
        profile_user = (TextView) findViewById(R.id.profile_user);
        profile_user_type = (TextView) findViewById(R.id.profile_user_type);
        txt_confirm_pin = (TextView) findViewById(R.id.txt_confirm_pin);
        round_img_pic = (RoundedImageView) findViewById(R.id.round_img_pic);
        btn_save_forgot = (FloatingActionButton) findViewById(R.id.btn_save_forgot);
        rl_otp_pinview = (LinearLayout) findViewById(R.id.rl_otp_pinview);

        card_forgot_password_layout = (CardView) findViewById(R.id.card_forgot_password_layout);
        card_view_forgot_password_top = (CardView) findViewById(R.id.card_view_forgot_password_top);

        user_spin = (Spinner) findViewById(R.id.user_spin);
        edt_password = (EditText) findViewById(R.id.edt_password);
        edt_confirm_password = (EditText) findViewById(R.id.edt_confirm_password);

        img_invisible.setOnClickListener(this);
        btn_save_forgot.setOnClickListener(this);
        img_info.setOnClickListener(this);
        bsListData = (ArrayList<BaListGetterSetter>) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        if (bsListData != null && bsListData.size() > 0) {
            setBrandSpinnerData(bsListData, user_spin);
        }
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }


        setTitle("Forgot Password  " + visit_date);
        user_spin.setOnItemSelectedListener(this);

        /* To restrict Space Bar in Keyboard */
        InputFilter filter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (Character.isWhitespace(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }

        };
        edt_password.setFilters(new InputFilter[]{filter});

        /* To restrict Space Bar in Keyboard */
        InputFilter filteredt_confirm = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    if (Character.isWhitespace(source.charAt(i))) {
                        return "";
                    }
                }
                return null;
            }

        };

        edt_confirm_password.setFilters(new InputFilter[]{filteredt_confirm});
    }


    private void setBrandSpinnerData(ArrayList<BaListGetterSetter> userList, Spinner user_spin) {
        user_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        user_adapter.add("- Select User -");

        for (int i = 0; i < userList.size(); i++) {
            user_adapter.add(userList.get(i).getUserName());
        }

        user_spin.setAdapter(user_adapter);
        user_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.img_invisible) {
            if (!otp_code.equals("") && card_view_forgot_password_top.getVisibility() == View.GONE) {
                // Its visible
                card_view_forgot_password_top.setVisibility(View.VISIBLE);
                img_invisible.setImageResource(R.mipmap.invisible);
            } else {
                // Either gone or invisible
                card_view_forgot_password_top.setVisibility(View.GONE);
                card_forgot_password_layout.setVisibility(View.VISIBLE);
                img_invisible.setImageResource(R.mipmap.visible);
            }

        } else if (view.getId() == R.id.btn_save_forgot) {
            submit();

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

        }

    }

    private void setpin_view() {
        pinview_otp.setPinViewEventListener(new Pinview.PinViewEventListener() {
            @Override
            public void onDataEntered(Pinview pinview, boolean fromUser) {
                if (!pinview.getValue().equals("") && otp_code != null && !otp_code.equals(""))
                    if (pinview.getValue().equals(otp_code)) {
                        card_view_forgot_password_top.setVisibility(View.GONE);
                        card_forgot_password_layout.setVisibility(View.VISIBLE);
                    }
            }
        });

    }

    private void set_user_icon() {
        Bitmap bitmp = null;
        if (user_type != null && !user_type.equals("") && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) {
            profile_user_type.setText("Beauty Advisor");
        } else if (user_type != null && !user_type.equals("") && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {
            profile_user_type.setText("Temp Beauty Advisor");
        } else if (user_type != null && !user_type.equals("") && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
            profile_user_type.setText("Makeup Expert");
        }

        db.open();
        MasterProfile baProfileGetterSetter = db.getBaProfileData(str_user_name, visit_date, false);
        db.open();
        ArrayList<MasterProfile> baProfileListData = db.getBAProfileListAllData(str_user_name, visit_date);
        if (!baProfileListData.isEmpty()) {
            profile_user.setText(baProfileListData.get(0).getFullName());
        } else {
            profile_user.setText("User Id - " + str_user_name);
        }

        if (baProfileGetterSetter.getProfilePic() != null && !baProfileGetterSetter.getProfilePic().equals("")) {
            if (new File(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic()).exists()) {
                bitmp = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic());
                round_img_pic.setImageBitmap(bitmp);
            } else {
                bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image);
                round_img_pic.setImageBitmap(bitmp);
            }
        } else if (baProfileListData.size() > 0 && baProfileListData.get(0).getProfilePic() != null && !baProfileListData.get(0).getProfilePic().equals("")) {
            if (CommonFunctions.checkNetIsAvailable(context))
                Picasso.with(context).load(baProfileListData.get(0).getProfilePic()).networkPolicy(NetworkPolicy.NO_CACHE).into(round_img_pic);
        } else {
            bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image);
            round_img_pic.setImageBitmap(bitmp);
        }
    }

    public void showAlert(String str, final boolean flag_finish) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        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) {
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    public void getotp_from_mobile_no(String jsondata) {
        try {
            loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false);
            final OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, 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.getOTPMethodForForgotpass(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.equals("") && !data.contains("Failure")) {
                                if (!data.isEmpty()) {
                                    String s[] = data.split(",");
                                    otp_code = s[0];
                                    String mobile_no = s[1].substring(6, 10);
                                    txt_confirm_pin.setText(getString(R.string.verification_code) + mobile_no);
                                    rl_otp_pinview.setVisibility(View.VISIBLE);
                                    user_spin.setEnabled(false);
                                    loading.dismiss();
                                }
                            } else {
                                loading.dismiss();
                                showAlert("Mobile Number Does Not Exist In Database. So Can Not Able to Reset Password", true);
                            }

                        } catch (Exception e) {
                            Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show();
                            e.fillInStackTrace();
                            loading.dismiss();
                        }
                    } else {
                        loading.dismiss();
                        Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlertlogin((Activity) context, t.toString());
                }
            });
        } catch (Exception e) {
            Toast.makeText(context, "Server Not Responding . Please Try Again.", Toast.LENGTH_SHORT).show();
            e.fillInStackTrace();
            loading.dismiss();
        }
    }

    void submit() {
        boolean cancel = false;
        View focusView = null;
        //New Password
        Pattern textPattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?=.*\\d).+$");
        if (user_spin.getSelectedItemId() == 0) {
            AlertandMessages.showToastMsg(context, "Please Select User");
            focusView = user_spin;
            cancel = true;
        } else if (pinview_otp.getValue().equals("")) {
            AlertandMessages.showToastMsg(context, "Please Enter OTP");
            focusView = pinview_otp;
            cancel = true;
        } else if (pinview_otp.getValue().length() != 4) {
            AlertandMessages.showToastMsg(context, "Please Enter Four Digit OTP");
            focusView = pinview_otp;
            cancel = true;
        } else if (!pinview_otp.getValue().equals(otp_code)) {
            AlertandMessages.showToastMsg(context, "Please Enter Correct OTP");
            focusView = pinview_otp;
            cancel = true;
        } else if (edt_password.getText().toString().equals("")) {
            AlertandMessages.showToastMsg(context, getString(R.string.error_field_required));
            focusView = edt_password;
            cancel = true;
        } else if (edt_password.getText().toString().length() >= 8 && textPattern.matcher(edt_password.getText().toString()).matches()) {
            String confirm_pw = edt_confirm_password.getText().toString();
            if (confirm_pw.equals("")) {
                AlertandMessages.showToastMsg(context, getString(R.string.error_field_required));
                focusView = edt_confirm_password;
                cancel = true;
            } else if (!confirm_pw.equals(edt_password.getText().toString())) {
                AlertandMessages.showToastMsg(context, getString(R.string.password_and_confirm_password_not_match));
                focusView = edt_confirm_password;
                cancel = true;
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData);
                builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        new AuthenticateTask().execute();

                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
                builder.show();
            }
        } else {
            AlertandMessages.showToastMsg(context, getString(R.string.invalid_password));
            focusView = edt_password;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();

        } else {

        }
    }

    @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);
                                ForgotpasswordActity.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);
                ForgotpasswordActity.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);
                            ForgotpasswordActity.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);
            ForgotpasswordActity.this.finish();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
        if (pos != 0) {
            str_user_name = bsListData.get(pos - 1).getUserName().toLowerCase();
            clicked_flag = true;
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("UserId", str_user_name);
                jsonObject.put("MobileNo", "");
                getotp_from_mobile_no(jsonObject.toString());
            } catch (JSONException e) {
                e.fillInStackTrace();
            }
        } else {
            str_user_name = "";

        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    private class AuthenticateTask extends AsyncTask<Void, Void, String> {
        private ProgressDialog dialog = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(context);
            dialog.setTitle("Updating Password");
            dialog.setMessage("Updating....");
            dialog.setCancelable(false);
            if (!dialog.isShowing()) {
                dialog.show();
            }
        }

        @Override
        protected String doInBackground(Void... params) {
            try {

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("UserId", str_user_name);
                jsonObject.put("NewPassword", edt_confirm_password.getText().toString());

                String jsonString2 = jsonObject.toString();
                DownloadAllDatawithRetro upload = new DownloadAllDatawithRetro(getApplicationContext());
                String result_str = upload.downloadDataUniversal(jsonString2, CommonString.FORGOT_PASSWORD_SERVICE);
                if (result_str.contains(CommonString.KEY_SUCCESS)) {
                    return CommonString.KEY_SUCCESS;
                } else {
                    return result_str;
                }

            } catch (Exception e) {
                dialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertandMessages.showAlert((Activity) context, CommonString.MESSAGE_EXCEPTION, false);
                    }
                });
            }

            return "";

        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result.equals(CommonString.KEY_SUCCESS)) {
                db.open();
                if (db.ischeck_login_data(str_user_name.toLowerCase())) {
                    db.open();
                    db.deleteTableWithLogin(str_user_name.toLowerCase());
                }
                if (user_id.toLowerCase().equals(str_user_name.toLowerCase())) {
                    editor.putString(CommonString.KEY_PASSWORD, "");
                    editor.putString(CommonString.MPIN, null);
                    editor.putString(CommonString.KEY_USERNAME, "");
                    editor.commit();
                }
                showAlert(getString(R.string.password_reset_successfully), true);
            } else {
                showAlert(result, false);
            }
        }
    }
}
