package com.cpm.lorealbaautomation.makeupexpert;

import android.annotation.SuppressLint;
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 com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
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.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
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.delegates.PrefHelper;
import com.cpm.lorealbaautomation.download.Downloader;
import com.cpm.lorealbaautomation.gsonGetterSetter.ConsumerTermsConditionAccept;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterBAProfileGetterSetter;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

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.constant.CommonFunctions.getCurrentTime;
import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

public class MakeoverDetailsActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    String CounterId, visit_date, username, str_termCondition = "0", response_term_condition = "", _pathforcheck = "", _path = "",
            otp_code = "", flag_for_makeover_Update = "", before_makeover_img_str = "", after_makeover_img_str = "", feed_back_str = "";
    boolean no_name_flag = false, no_mobile_no_flag = false, flag_for_term_condition = false, clicked_flag = false, feed_back_flag = false;
    ArrayAdapter<CharSequence> AgeAdapter, SkinTypeAdapter, lookCreatedAdapter;
    public ArrayList<InvoiceGetterSetter> selected_list = new ArrayList<>();
    EditText edt_customer, edt_mobile_no, edt_otp, edt_email_address;
    Spinner spin_age, spin_skin_type, spin_look_created;
    ImageView img_before_makeover, img_after_makeover;
    JourneyPlan storeDataObject = new JourneyPlan();
    private SharedPreferences.Editor editor = null;
    CheckBox mobile_checkbox, no_name_checkbox;
    TextView rl_term_condition, text_user_nm;
    private SharedPreferences preferences;
    FloatingActionButton fab, draft_fab;
    MultiPurposeDialog multidialog;
    private RadioButton radioSexButton;
    private RadioGroup radioSexGroup;
    InvoiceGetterSetter object;
    ScrollView scroll_view;
    ProgressDialog loading;
    ///new changes19/08/19
    Lorealba_Database db;
    LinearLayout rl_otp;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_makeover_details);
        context = this;
        ((MakeoverDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        iduserinterface();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Makeover Details -" + username);

    }

    @SuppressLint("RestrictedApi")
    private void iduserinterface() {
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        scroll_view = (ScrollView) findViewById(R.id.scroll_view);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        draft_fab = (FloatingActionButton) findViewById(R.id.draft_fab);
        edt_customer = (EditText) findViewById(R.id.edt_customer);
        edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no);
        mobile_checkbox = (CheckBox) findViewById(R.id.mobile_checkbox);
        no_name_checkbox = (CheckBox) findViewById(R.id.no_name_checkbox);
        radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp);
        ///new changes19--08-19
        rl_term_condition = (TextView) findViewById(R.id.rl_term_condition);
        text_user_nm = (TextView) findViewById(R.id.text_user_nm);
        rl_otp = (LinearLayout) findViewById(R.id.rl_otp);
        edt_otp = (EditText) findViewById(R.id.edt_otp);
        edt_email_address = (EditText) findViewById(R.id.edt_email_address);
        spin_age = (Spinner) findViewById(R.id.spin_age);
        spin_skin_type = (Spinner) findViewById(R.id.spin_skin_type);
        spin_look_created = (Spinner) findViewById(R.id.spin_look_created);
        img_before_makeover = (ImageView) findViewById(R.id.img_before_makeover);
        img_after_makeover = (ImageView) findViewById(R.id.img_after_makeover);

        fab.setOnClickListener(this);
        mobile_checkbox.setOnClickListener(this);
        no_name_checkbox.setOnClickListener(this);
        draft_fab.setOnClickListener(this);
        rl_otp.setOnClickListener(this);
        rl_term_condition.setOnClickListener(this);
        img_after_makeover.setOnClickListener(this);
        img_before_makeover.setOnClickListener(this);
        db.open();
        storeDataObject = db.getspecific_storenamewith_counter_name(visit_date, CounterId, username);
        flag_for_makeover_Update = getIntent().getStringExtra(CommonString.Key_For_Consumer_Update);
        selected_list = (ArrayList<InvoiceGetterSetter>) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        if (flag_for_makeover_Update != null && flag_for_makeover_Update.equals("1")) {
            edt_mobile_no.setEnabled(false);
            rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            rl_term_condition.setEnabled(false);
            mobile_checkbox.setEnabled(false);
        } else if (flag_for_makeover_Update != null && flag_for_makeover_Update.equals("0")) {

            draft_fab.setVisibility(View.GONE);
            fab.setVisibility(View.GONE);
            no_name_checkbox.setEnabled(false);
            mobile_checkbox.setEnabled(false);
            edt_customer.setEnabled(false);
            edt_mobile_no.setEnabled(false);
            rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            rl_term_condition.setEnabled(false);
            mobile_checkbox.setEnabled(false);
            edt_email_address.setEnabled(false);
            spin_age.setEnabled(false);
            spin_skin_type.setEnabled(false);
            spin_look_created.setEnabled(false);
            radioSexGroup.setEnabled(false);
            img_before_makeover.setEnabled(false);
            img_after_makeover.setEnabled(false);
        }

        if (selected_list != null && selected_list.size() > 0) {
            object = selected_list.get(0);
            username = object.getUserName();
            edt_customer.setText(object.getCustomer_name().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
            edt_mobile_no.setText(object.getMobile_no());
            edt_email_address.setText(object.getConsumer_email_Id());
            str_termCondition = object.getStr_termcondition();
            /////for radio group
            if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Male")) {
                //radioSexButton
                radioSexGroup.check(R.id.radioM);
            } else if (selected_list.get(0).getCustomer_gender().equalsIgnoreCase("Female")) {
                //radioSexButton
                radioSexGroup.check(R.id.radioF);
            } else {
                radioSexGroup.check(R.id.radio_other);
            }

            if (!object.getBefore_makeover_img().equals("")) {
                img_before_makeover.setImageResource((R.mipmap.camera_bsd));
                before_makeover_img_str = object.getBefore_makeover_img();
                img_before_makeover.setEnabled(false);
            }

            if (!object.getAfter_makeover_img().equals("")) {
                img_after_makeover.setImageResource((R.mipmap.camera_bsd));
                after_makeover_img_str = object.getAfter_makeover_img();
            }
        }

        ///calling of age adapter
        adapterforAgeLimit_SkinType();
        getstatusof_termcondition();
    }

    private boolean checkotp_validation() {
        boolean status = true;
        if (edt_otp.getText().toString().equals("0000")) {
            status = true;
            str_termCondition = "1";
        } else if (edt_otp.getText().toString().equals(otp_code)) {
            status = true;
            str_termCondition = "1";
        } else {
            status = false;
        }

        return status;

    }

    private void custom_dialog_for_termand_condition(final Context context) {
        multidialog = new MultiPurposeDialog(context);
        multidialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multidialog.setContentView(R.layout.custom_dialog_for_term_condition);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(multidialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multidialog.getWindow().setAttributes(lp);
        multidialog.setCancelable(false);
        ///new changes 19 aug
        CheckBox checkbox_accept = (CheckBox) multidialog.findViewById(R.id.checkbox_accept);
        CheckBox checkbox_reject = (CheckBox) multidialog.findViewById(R.id.checkbox_reject);
        TextView txt_term_condition = (TextView) multidialog.findViewById(R.id.txt_term_condition);

        if (flag_for_term_condition) {
            checkbox_accept.setChecked(true);
        }

        db.open();
        txt_term_condition.setText(db.getterm_and_condition().getTermsCondition());

        checkbox_accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    flag_for_term_condition = true;
                    multidialog.dismiss();
                    rl_otp.setVisibility(View.VISIBLE);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("MobileNumber", edt_mobile_no.getText().toString());
                    getotp_from_mobile_no(jsonObject.toString());
                } catch (JSONException e) {
                    e.fillInStackTrace();
                }
            }
        });

        checkbox_reject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multidialog.dismiss();
                rl_otp.setVisibility(View.GONE);
                flag_for_term_condition = false;
                rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
                rl_term_condition.setEnabled(false);
            }
        });

        multidialog.show();
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.img_before_makeover) {
            _pathforcheck = CounterId + "_before_makeo_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
        } else if (view.getId() == R.id.img_after_makeover) {
            if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) {
                _pathforcheck = CounterId + "_after_makeo_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
            }

        } else if (view.getId() == R.id.rl_term_condition) {
            if (checkindex()) {
                custom_dialog_for_termand_condition(context);
            }

        } else if (view.getId() == R.id.mobile_checkbox) {
            clicked_flag = true;
            if (mobile_checkbox.isChecked()) {
                no_mobile_no_flag = true;
                flag_for_term_condition = false;
                edt_mobile_no.setText("0000000000");
                rl_otp.setVisibility(View.GONE);
                edt_mobile_no.setEnabled(false);
                rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            } else {
                edt_mobile_no.setText("");
                no_mobile_no_flag = false;
                edt_mobile_no.setEnabled(true);
                rl_term_condition.setTextColor(getResources().getColor(R.color.blue));
            }

        } else if (view.getId() == R.id.no_name_checkbox) {
            clicked_flag = true;
            if (no_name_checkbox.isChecked()) {
                no_name_flag = true;
                edt_customer.setText("No Name");
                edt_customer.setEnabled(false);
            } else {
                edt_customer.setText("");
                no_name_flag = false;
                edt_customer.setEnabled(true);
            }

        } else if (view.getId() == R.id.fab) {
            if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) {
                CustomerfeedBack_dialog(context);
            }

            ((MakeoverDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number ");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Check Terms & Condition");
            } else if (!edt_email_address.getText().toString().isEmpty() &&
                    !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            } else if (spin_age.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Age Range");
            } else if (spin_skin_type.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Type ");
            } else if (spin_look_created.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Look Created");
            } else if (!no_mobile_no_flag && flag_for_term_condition && edt_otp.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter OTP");
            } else if (!no_mobile_no_flag && flag_for_term_condition && !checkotp_validation()) {
                AlertandMessages.showToastMsg(context, "Incorrect OTP");
            } else if (before_makeover_img_str.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Capture Before Makeover Image");
            } else if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1") && after_makeover_img_str.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Capture After Makeover Image");
            } else if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1") && !feed_back_flag) {
                AlertandMessages.showToastMsg(context, "Please Choose Customer Feedback");
            } 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) {
                        try {
                            InvoiceGetterSetter maekoverobject = new InvoiceGetterSetter();
                            // get selected radio button from radioGroup
                            int selectedId = radioSexGroup.getCheckedRadioButtonId();
                            // find the radiobutton by returned id
                            radioSexButton = (RadioButton) findViewById(selectedId);
                            maekoverobject.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)1234567890\"]", ""));
                            maekoverobject.setMobile_no(edt_mobile_no.getText().toString());
                            maekoverobject.setConsumer_email_Id(edt_email_address.getText().toString());

                            if (spin_age.getSelectedItemId() == 0) {
                                maekoverobject.setConsumer_age("");
                            } else {
                                maekoverobject.setConsumer_age(spin_age.getSelectedItem().toString());
                            }

                            if (spin_skin_type.getSelectedItemId() == 0) {
                                maekoverobject.setConsumer_skinType("");
                            } else {
                                maekoverobject.setConsumer_skinType(spin_skin_type.getSelectedItem().toString());
                            }

                            if (spin_look_created.getSelectedItemId() == 0) {
                                maekoverobject.setLook_creater_str("");
                            } else {
                                maekoverobject.setLook_creater_str(spin_look_created.getSelectedItem().toString());
                            }

                            maekoverobject.setCustomer_gender(radioSexButton.getText().toString());
                            maekoverobject.setBefore_makeover_img(before_makeover_img_str);
                            maekoverobject.setAfter_makeover_img(after_makeover_img_str);
                            maekoverobject.setCst_feed_back_value(feed_back_str);
                            maekoverobject.setStr_termcondition(str_termCondition);
                            maekoverobject.setUnique_code(CommonFunctions.getUUID(context));
                            maekoverobject.setPos_sale_flag(false);
                            if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) {
                                db.open();
                                maekoverobject.setPos_sale_flag(true);
                                maekoverobject.setReccept_count(object.getReccept_count());
                                db.update_makeover_capture(CounterId, visit_date, username, maekoverobject);
                                //download service
                                Intent intent = new Intent(context, Downloader.class);
                                intent.putExtra(CommonString.KEY_Me_MakeOver_Capture, maekoverobject);
                                Downloader.enqueueWork(context, intent);

                            } else {
                                db.open();
                                db.insert_makeover_capture(username, visit_date, CounterId, maekoverobject);
                            }

                            AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            MakeoverDetailsActivity.this.finish();
                            dialogInterface.dismiss();

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

                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });

                builder.show();
            }

        } else if (view.getId() == R.id.draft_fab) {
            ((MakeoverDetailsActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (!no_name_flag && edt_customer.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Customer Name");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            } else if (!no_mobile_no_flag && edt_mobile_no.getText().toString().length() < 10) {
                AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number");
            } else if (checkindex() && rl_term_condition.isEnabled() && otp_code.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Check Terms & Condition");
            } else if (!edt_email_address.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email_address.getText().toString())) {
                AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id");
            } else if (spin_age.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Age Range ");
            } else if (spin_skin_type.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Skin Type");
            } else if (spin_look_created.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Look Created");
            } else if (flag_for_term_condition && edt_otp.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Enter OTP");
            } else if (flag_for_term_condition && !checkotp_validation()) {
                AlertandMessages.showToastMsg(context, "Incorrect OTP");
            } else if (before_makeover_img_str.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Capture Before Makeover Image");
            } else if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1") && after_makeover_img_str.equals("")) {
                AlertandMessages.showToastMsg(context, "Please Capture After Makeover Image");
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.alertsaveData);
                builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                    InvoiceGetterSetter maekoverobject = new InvoiceGetterSetter();
                    // get selected radio button from radioGroup
                    int selectedId = radioSexGroup.getCheckedRadioButtonId();
                    // find the radiobutton by returned id
                    radioSexButton = (RadioButton) findViewById(selectedId);
                    maekoverobject.setCustomer_name(edt_customer.getText().toString().trim().replaceAll("[(!@#$%^&*?)1234567890\"]", ""));
                    maekoverobject.setMobile_no(edt_mobile_no.getText().toString());
                    maekoverobject.setConsumer_email_Id(edt_email_address.getText().toString());
                    if (spin_age.getSelectedItemId() == 0) {
                        maekoverobject.setConsumer_age("");
                    } else {
                        maekoverobject.setConsumer_age(spin_age.getSelectedItem().toString());
                    }
                    if (spin_skin_type.getSelectedItemId() == 0) {
                        maekoverobject.setConsumer_skinType("");
                    } else {
                        maekoverobject.setConsumer_skinType(spin_skin_type.getSelectedItem().toString());
                    }

                    if (spin_look_created.getSelectedItemId() == 0) {
                        maekoverobject.setLook_creater_str("");
                    } else {
                        maekoverobject.setLook_creater_str(spin_look_created.getSelectedItem().toString());
                    }

                    maekoverobject.setCustomer_gender(radioSexButton.getText().toString());
                    maekoverobject.setBefore_makeover_img(before_makeover_img_str);
                    maekoverobject.setAfter_makeover_img(after_makeover_img_str);
                    maekoverobject.setCst_feed_back_value(feed_back_str);
                    maekoverobject.setStr_termcondition(str_termCondition);
                    maekoverobject.setUnique_code(CommonFunctions.getUUID(context));
                    maekoverobject.setPos_sale_flag(false);
                    if (flag_for_makeover_Update != null && !flag_for_makeover_Update.equals("") && flag_for_makeover_Update.equals("1")) {
                        db.open();
                        maekoverobject.setReccept_count(object.getReccept_count());
                        db.update_makeover_capture(CounterId, visit_date, username, maekoverobject);
                    } else {
                        db.open();
                        db.insert_makeover_capture(username, visit_date, CounterId, maekoverobject);
                    }

                    AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                    MakeoverDetailsActivity.this.finish();
                    dialogInterface.dismiss();
                });

                builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());

                builder.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);
                                MakeoverDetailsActivity.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);
                MakeoverDetailsActivity.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);
                            MakeoverDetailsActivity.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);
            MakeoverDetailsActivity.this.finish();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
        switch (adapterView.getId()) {
        }
    }

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

    }

    public class MultiPurposeDialog extends Dialog {
        public MultiPurposeDialog(Context context) {
            super(context);
            // DIALOG USER_INTERFACE TEMPLATE
            WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes();
            wmLayoutParams.gravity = Gravity.CENTER;
            getWindow().setAttributes(wmLayoutParams);
            setTitle(null);
            setCancelable(false);
            setOnCancelListener(null);
            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result == null) {
            switch (resultCode) {
                case 0:
                    Log.i("MakeMachine", "User cancelled");
                    break;

                case -1:
                    if (_pathforcheck != null && !_pathforcheck.equals("")) {
                        try {
                            if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                                convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                                if (_pathforcheck.contains("_before_makeo_img_")) {
                                    before_makeover_img_str = _pathforcheck;
                                    img_before_makeover.setImageResource((R.mipmap.camera_bsd));
                                } else {
                                    after_makeover_img_str = _pathforcheck;
                                    img_after_makeover.setImageResource((R.mipmap.camera_bsd));
                                }

                                _pathforcheck = "";
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                        }
                    }

                    break;
            }

        } else
            super.onActivityResult(requestCode, resultCode, data);
    }

    public void getotp_from_mobile_no(String jsondata) {
        try {
            loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false);
            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.toString());
            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.getOTPMethod(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();
                            JSONObject jObject = new JSONObject(data);
                            otp_code = jObject.getString("SendOTPResult");
                            loading.dismiss();

                        } catch (Exception e) {
                            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) {
            e.fillInStackTrace();
            loading.dismiss();
        }
    }

    private boolean checkindex() {
        boolean status = false;
        String str = edt_mobile_no.getText().toString();
        String strArray[] = str.split(" ");
        //print elements of String array
        for (int i = 0; i < strArray.length; i++) {
            if (strArray[i].contains("1") || strArray[i].contains("2") || strArray[i].contains("3") || strArray[i].contains("4") || strArray[i].contains("5") || strArray[i].contains("6") || strArray[i].contains("7") || strArray[i].contains("9") || strArray[i].contains("8")) {
                status = true;
                break;
            }
        }
        return status;
    }

    private void getstatusof_termcondition() {
        edt_mobile_no.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().equals("") && editable.toString().length() == 10) {
                    if (CommonFunctions.checkNetIsAvailable(context) && checkindex()) {
                        try {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("Downloadtype", "Consumer_TermsConditionAccept");
                            jsonObject1.put("Username", username);
                            jsonObject1.put("Param2", CounterId);
                            jsonObject1.put("Param1", edt_mobile_no.getText().toString());
                            getstatusoftermscondition_status(context, jsonObject1.toString());
                        } catch (JSONException e) {
                            e.fillInStackTrace();
                        }
                    } else {
                        response_term_condition = "0";
                    }
                } else {
                    rl_term_condition.setTextColor(getResources().getColor(R.color.blue));
                    rl_term_condition.setEnabled(true);
                }
            }
        });

    }

    public void getstatusoftermscondition_status(final Context context, String jsondata) {
        try {
            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.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            retrofit2.Call<String> call = api.getDownloadAll(jsonData);
            call.enqueue(new retrofit2.Callback<String>() {
                @Override
                public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
                    String responseBody = response.body();
                    String data_for = null;
                    if (responseBody != null && response.isSuccessful()) {
                        data_for = response.body();
                        if (data_for.equals("")) {
                        } else {
                            if (!data_for.contains("No Data")) {
                                MasterBAProfileGetterSetter reportbaAvailabilityGetterSetter = new Gson().fromJson(data_for, MasterBAProfileGetterSetter.class);
                                if (reportbaAvailabilityGetterSetter != null) {
                                    List<ConsumerTermsConditionAccept> dataresponce = reportbaAvailabilityGetterSetter.getConsumerTermsConditionAccept();
                                    if (dataresponce.get(0).getTermsConditionAccept()) {
                                        response_term_condition = "1";

                                        rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
                                        rl_term_condition.setEnabled(false);

                                    } else {
                                        response_term_condition = "0";
                                    }
                                } else {
                                    response_term_condition = "0";
                                }

                            } else {
                                response_term_condition = "0";
                            }
                        }
                    } else {
                        loading.dismiss();
                        response_term_condition = "0";
                    }
                }

                @Override
                public void onFailure(retrofit2.Call<String> call, Throwable t) {
                    loading.dismiss();
                    response_term_condition = "0";
                }
            });
        } catch (Exception e) {
            e.fillInStackTrace();
            response_term_condition = "0";
            loading.dismiss();
        }
    }

    private void adapterforAgeLimit_SkinType() {
        AgeAdapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        AgeAdapter.add("- Select Age Range -");
        db.open();
        for (int i = 0; i < db.getAgeLimitMasterData().size(); i++) {
            AgeAdapter.add(db.getAgeLimitMasterData().get(i).getAgeLimit());
        }
        spin_age.setAdapter(AgeAdapter);
        AgeAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spin_age.setOnItemSelectedListener(this);

        SkinTypeAdapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        SkinTypeAdapter.add("- Select Skin Type -");
        for (int i = 0; i < db.getskinTypeMaster().size(); i++) {
            SkinTypeAdapter.add(db.getskinTypeMaster().get(i).getSkinType());
        }
        spin_skin_type.setAdapter(SkinTypeAdapter);
        SkinTypeAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spin_skin_type.setOnItemSelectedListener(this);

        lookCreatedAdapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        lookCreatedAdapter.add("- Select Look -");
        for (int i = 0; i < db.getlook_creation().size(); i++) {
            lookCreatedAdapter.add(db.getlook_creation().get(i).getLooks());
        }
        spin_look_created.setAdapter(lookCreatedAdapter);
        lookCreatedAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spin_look_created.setOnItemSelectedListener(this);


        if (flag_for_makeover_Update != null && flag_for_makeover_Update.equals("1") || flag_for_makeover_Update != null && flag_for_makeover_Update.equals("0")) {
            db.open();
            for (int k = 0; k < db.getAgeLimitMasterData().size(); k++) {
                if (!object.getConsumer_age().equals(""))
                    if (db.getAgeLimitMasterData().get(k).getAgeLimit().equals(object.getConsumer_age())) {
                        spin_age.setSelection(k + 1);
                        break;
                    }
            }
            db.open();
            for (int k = 0; k < db.getskinTypeMaster().size(); k++) {
                if (!object.getConsumer_skinType().equals(""))
                    if (db.getskinTypeMaster().get(k).getSkinType().equals(object.getConsumer_skinType())) {
                        spin_skin_type.setSelection(k + 1);
                        break;
                    }
            }
            db.open();
            for (int k = 0; k < db.getlook_creation().size(); k++) {
                if (!object.getLook_creater_str().equals(""))
                    if (db.getlook_creation().get(k).getLooks().equals(object.getLook_creater_str())) {
                        spin_look_created.setSelection(k + 1);
                        break;
                    }
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!response_term_condition.equals("") && !response_term_condition.equals("0")) {
            rl_term_condition.setTextColor(getResources().getColor(R.color.gray));
            rl_term_condition.setEnabled(false);
        }
    }

    private boolean CustomerfeedBack_dialog(final Context context) {
        final MultiPurposeDialog multiPurposeDialog = new MultiPurposeDialog(context);
        multiPurposeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        multiPurposeDialog.setContentView(R.layout.customer_feedback_dialog);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(multiPurposeDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        multiPurposeDialog.getWindow().setAttributes(lp);
        multiPurposeDialog.setCancelable(false);

        final ImageView excellent = (ImageView) multiPurposeDialog.findViewById(R.id.excellent);
        final ImageView very_good = (ImageView) multiPurposeDialog.findViewById(R.id.very_good);
        final ImageView good_img = (ImageView) multiPurposeDialog.findViewById(R.id.good);
        final ImageView img_bad = (ImageView) multiPurposeDialog.findViewById(R.id.img_bad);
        final ImageView ok = (ImageView) multiPurposeDialog.findViewById(R.id.ok);

        excellent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feed_back_str = "Excellent";
                excellent.setImageResource((R.mipmap.tick_excellent));
                very_good.setImageResource((R.mipmap.emogi_verygood));
                good_img.setImageResource((R.mipmap.emogi_good));
                img_bad.setImageResource((R.mipmap.emogi_bad));
            }
        });

        very_good.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feed_back_str = "Very Good";
                excellent.setImageResource((R.mipmap.emogi_excellent));
                very_good.setImageResource((R.mipmap.tick_verygood));
                good_img.setImageResource((R.mipmap.emogi_good));
                img_bad.setImageResource((R.mipmap.emogi_bad));

            }
        });

        good_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feed_back_str = "Good";
                excellent.setImageResource((R.mipmap.emogi_excellent));
                very_good.setImageResource((R.mipmap.emogi_verygood));
                good_img.setImageResource((R.mipmap.tick_good));
                img_bad.setImageResource((R.mipmap.emogi_bad));
            }
        });
        img_bad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feed_back_str = "Bad";
                excellent.setImageResource((R.mipmap.emogi_excellent));
                very_good.setImageResource((R.mipmap.emogi_verygood));
                good_img.setImageResource((R.mipmap.emogi_good));
                img_bad.setImageResource((R.mipmap.tick_bad));
            }
        });


        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (feed_back_str.equals("")) {
                    AlertandMessages.showToastMsg(context, "Please Choose Customer Feedback");
                    feed_back_flag = false;
                } else {
                    feed_back_flag = true;
                    multiPurposeDialog.dismiss();
                }
            }
        });


        final ImageView dismiss_dialog = (ImageView) multiPurposeDialog.findViewById(R.id.dismiss_dialog);
        dismiss_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiPurposeDialog.dismiss();
            }
        });


        if (!feed_back_flag) {
            multiPurposeDialog.show();
        }

        return feed_back_flag;
    }

}
