package com.cpm.lorealbaautomation.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

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

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.androidbuts.multispinnerfilter.KeyPairBoolData;
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.download.Downloader;
import com.cpm.lorealbaautomation.gettersetter.AuditDataGetterSetter;
import com.cpm.lorealbaautomation.gettersetter.BaProfileGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfile;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestion;
import com.cpm.lorealbaautomation.makeupexpert.BaProfileMultiSelection;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime;
import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

public class BAProfileActivity extends AppCompatActivity implements View.OnClickListener {
    EditText edt_employee_code, edt_full_name, supervisor_name, edt_address, edt_brand, edt_counter, edt_store_name, edt_location, edt_mobile_no, edt_email, edt_enstagram_address, edt_city, edt_current_bp;
    EditText edt_landmark;
    ImageView img_dob;
    Toolbar toolbar;
    TextView storeProfile_dob;
    private RoundedImageView round_img_pic;
    ArrayList<MasterProfile> baProfileListData = new ArrayList<>();
    Lorealba_Database db;
    SharedPreferences preferences;
    SharedPreferences.Editor editor = null;
    Context context;
    String counterId, visitdate, user_type;
    boolean update_flag = false;
    String user_name;
    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    List<Integer> checkHeaderArray = new ArrayList<>();
    List<Integer> checkGroupArray = new ArrayList<>();
    boolean checkflag = true;
    String pathforcheck = "", _path = "", str, img_str = "";
    ArrayList<AuditDataGetterSetter> question_list, childListData;
    HashMap<AuditDataGetterSetter, ArrayList<AuditDataGetterSetter>> hashMapAnsListChildData;
    int child_position = -1;
    String error_msg = "";
    ExpandableListView expandableListView;
    ExpandableListAdapter adapter;
    ArrayList<MasterProfileQuestion> listDataHeader = new ArrayList<>();
    HashMap<MasterProfileQuestion, ArrayList<AuditDataGetterSetter>> listDataChild;
    FloatingActionButton fab;
    ArrayList<JourneyPlan> storelist = new ArrayList<>();
    String merCd;
    MasterProfile baProfileGetterSetter = new MasterProfile();
    boolean multitouch = false;
    Bitmap bitmp;
    private RadioGroup radioSexGroup;
    TextView profile_user, profile_user_type;
    boolean backpress_flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baprofile);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        getViewId();
        validate();
        getQuizProfileData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        context = this;
        db.open();
    }


    void getViewId() {
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        str = CommonString.getImagesFolder(context);
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visitdate = preferences.getString(CommonString.KEY_DATE, "");
        user_name = preferences.getString(CommonString.KEY_USERNAME, "");
        user_type = preferences.getString(CommonString.KEY_USER_TYPE, "");
        radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp);
        edt_employee_code = (EditText) findViewById(R.id.edt_employee_code);
        edt_full_name = (EditText) findViewById(R.id.edt_full_name);
        supervisor_name = (EditText) findViewById(R.id.supervisor_name);

        edt_address = (EditText) findViewById(R.id.edt_address);
        storeProfile_dob = (TextView) findViewById(R.id.storeProfile_dob);
        profile_user = (TextView) findViewById(R.id.profile_user);
        profile_user_type = (TextView) findViewById(R.id.profile_user_type);
        edt_brand = (EditText) findViewById(R.id.edt_brand);
        edt_counter = (EditText) findViewById(R.id.edt_counter);
        edt_store_name = (EditText) findViewById(R.id.edt_store_name);
        edt_location = (EditText) findViewById(R.id.edt_location);
        edt_city = (EditText) findViewById(R.id.edt_city);
        edt_mobile_no = (EditText) findViewById(R.id.edt_mobile_no);
        edt_email = (EditText) findViewById(R.id.edt_email);
        edt_enstagram_address = (EditText) findViewById(R.id.edt_enstagram_address);
        edt_current_bp = (EditText) findViewById(R.id.edt_current_bp);
        edt_landmark = (EditText) findViewById(R.id.edt_landmark);
        img_dob = (ImageView) findViewById(R.id.img_dob);
        round_img_pic = (RoundedImageView) findViewById(R.id.round_img_pic);
        toolbar = findViewById(R.id.toolbar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) {
            setTitle(getString(R.string.ba_profile_data) + " - " + user_name);
        } else if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {
            setTitle("TBA Profile - " + user_name);
        } else if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
            setTitle("ME Profile - " + user_name);
        }
        img_dob.setOnClickListener(this);
        round_img_pic.setOnClickListener(this);
        db.open();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.img_dob) {
            c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            // Launch Date Picker Dialog
            dpd = new DatePickerDialog(this, (view1, year, monthOfYear, dayOfMonth) -> {
                String dob = (monthOfYear + 1) + "/" + dayOfMonth + "/" + year;
                storeProfile_dob.setText(dob);
            }, mYear, mMonth, mDay);
            dpd.getDatePicker().setMaxDate(System.currentTimeMillis());
            dpd.show();
        } else if (view.getId() == R.id.round_img_pic) {
            pathforcheck = counterId + "_ba_profile_img_" + user_name + "_" + visitdate.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + pathforcheck;
            CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
            backpress_flag = true;
        }
    }

    public ArrayList<String> getFileNames(File[] file) {
        ArrayList<String> arrayFiles = new ArrayList<String>();
        if (file != null) {
            for (File value : file) arrayFiles.add(value.getName());
        }
        return arrayFiles;
    }

    private void deleteexistingfile() {
        File dir = new File(CommonString.getProfileFolder(context));
        ArrayList<String> list1;
        list1 = getFileNames(dir.listFiles());
        try {
            if (list1 != null && !list1.isEmpty()) {
                for (int k = 0; k < list1.size(); k++) {
                    if (list1.get(k).contains("_ba_profile_img_" + user_name)) {
                        File originalFile = new File(CommonString.getProfileFolder(context) + list1.get(k));
                        originalFile.delete();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    void getQuizProfileData() {
        hashMapAnsListChildData = new HashMap<>();
        childListData = new ArrayList<>();
        expandableListView = (ExpandableListView) findViewById(R.id.list);
        db.open();
        listDataHeader = db.getAuditQuestionCategoryData(user_type);
        question_list = new ArrayList<>();
        listDataChild = new HashMap<>();
        if (!listDataHeader.isEmpty()) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                question_list = new ArrayList<>();
                db.open();
                question_list = db.getAfterSaveAuditQuestionAnswerData(user_name, listDataHeader.get(i).getCategoryId().toString());
                if (question_list.isEmpty()) {
                    db.open();
                    question_list = db.getSaveServerData(listDataHeader.get(i).getCategoryId().toString(), user_name);
                    if (question_list.isEmpty()) {
                        db.open();
                        question_list = db.getAuditCategoryWise(listDataHeader.get(i).getCategoryId());
                    }
                }

                if (!question_list.isEmpty()) {
                    String select = getString(R.string.title_activity_select_dropdown);
                    // Adding child data
                    for (int j = 0; j < question_list.size(); j++) {
                        db.open();
                        childListData = db.getAuditAnswerData(question_list.get(j), select);
                        if (question_list.get(j).getANSWER_TYPE().equalsIgnoreCase("Multi selection")) {
                            if (question_list.get(j).getANSWER() != null) {
                                final ArrayList<KeyPairBoolData> finalSelectedSamplingData = getKeyPairBoolData(j);
                                question_list.get(j).setSelectedSamplingData(finalSelectedSamplingData);
                            }
                        }
                        ArrayList<AuditDataGetterSetter> answerList = new ArrayList<>(childListData);
                        hashMapAnsListChildData.put(question_list.get(j), answerList); // Header, Child data
                    }
                }

                listDataChild.put(listDataHeader.get(i), question_list);
            }

            adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
            expandableListView.setAdapter(adapter);
            expandableListView.setAdapter(adapter);
            for (int i = 0; i < adapter.getGroupCount(); i++) {
                expandableListView.expandGroup(i);
            }
        } else {
            expandableListView.setVisibility(View.GONE);
        }

        expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                expandableListView.invalidate();
                int lastItem = firstVisibleItem + visibleItemCount;
                if (firstVisibleItem == 0) {
                    fab.show();//.setVisibility(View.VISIBLE);
                } else if (lastItem == totalItemCount) {
                    fab.hide();//setVisibility(View.INVISIBLE);
                } else {
                    fab.show();//setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }

                expandableListView.invalidateViews();
            }
        });


        fab.setOnClickListener(view -> {
            expandableListView.clearFocus();
            expandableListView.invalidateViews();
            baProfileGetterSetter.setLandmark(edt_landmark.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
            baProfileGetterSetter.setLocation(edt_location.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
            baProfileGetterSetter.setAddress(edt_address.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));
            baProfileGetterSetter.setDob(storeProfile_dob.getText().toString());
            baProfileGetterSetter.setMobile(edt_mobile_no.getText().toString().trim());
            baProfileGetterSetter.setEmail(edt_email.getText().toString().trim());
            baProfileGetterSetter.setInstragramAddress(edt_enstagram_address.getText().toString());
            if (validateimg_str()) {
                if (validateData(listDataHeader, listDataChild)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam);
                    builder.setMessage(R.string.title_activity_Want_save).setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> {
                        db.open();
                        db.insertBaProfiledata(counterId, user_name, user_type, visitdate, baProfileGetterSetter);
                        if (!listDataHeader.isEmpty()) {
                            db.open();
                            db.saveAuditQuestionAnswerData(listDataChild, listDataHeader, user_name, visitdate);
                        }
                        //upload service
                        Intent intent = new Intent(BAProfileActivity.this, Downloader.class);
                        BaProfileGetterSetter baProfileList = new BaProfileGetterSetter();
                        ArrayList<AuditDataGetterSetter> data = new ArrayList<>();
                        for (int i = 0; i < listDataHeader.size(); i++) {
                            List<AuditDataGetterSetter> list = listDataChild.get(listDataHeader.get(i));
                            if (list != null && !list.isEmpty()) data.addAll(list);
                        }
                        if (!data.isEmpty()) {
                            baProfileList.setBaProfileList(data);
                            intent.putExtra(CommonString.KEY_BaProfile, baProfileGetterSetter);
                            intent.putExtra(CommonString.KEY_BaProfile_list, baProfileList);
                            Downloader.enqueueWork(BAProfileActivity.this, intent);
                        }
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        BAProfileActivity.this.finish();
                    }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel());
                    AlertDialog alert = builder.create();
                    alert.show();
                } else {
                    AlertandMessages.showToastMsg(context, error_msg);
                }
            }
        });

        expandableListView.clearFocus();
    }

    private @NonNull ArrayList<KeyPairBoolData> getKeyPairBoolData(int j) {
        final ArrayList<KeyPairBoolData> finalSelectedSamplingData = new ArrayList<>();
        for (int k = 0; k < childListData.size(); k++) {
            KeyPairBoolData h1 = new KeyPairBoolData();
            h1.setAnswerCd(childListData.get(k).getANSWER_ID());
            h1.setName(childListData.get(k).getANSWER());
            h1.setSelected(question_list.get(j).getANSWER().contains(childListData.get(k).getANSWER()));
            finalSelectedSamplingData.add(h1);
        }
        return finalSelectedSamplingData;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (backpress_flag) {
                alert();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (backpress_flag) {
            alert();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            finish();
        }
    }

    private void alert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.dialog_title);
        builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false).setPositiveButton(getString(R.string.ok), (dialog, id) -> {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            finish();
        }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
        AlertDialog alert = builder.create();
        alert.show();
    }

    public class ExpandableListAdapter extends BaseExpandableListAdapter {
        Context _context;
        ArrayList<MasterProfileQuestion> listDataHeader; // header titles
        HashMap<MasterProfileQuestion, ArrayList<AuditDataGetterSetter>> listDataChild;

        public ExpandableListAdapter(Context context, ArrayList<MasterProfileQuestion> listDataHeader, HashMap<MasterProfileQuestion, ArrayList<AuditDataGetterSetter>> listDataChild) {
            this._context = context;
            this.listDataHeader = listDataHeader;
            this.listDataChild = listDataChild;
        }

        @Override
        public Object getChild(int groupPosition, int childPosititon) {
            return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @SuppressLint({"NewApi", "ClickableViewAccessibility", "InflateParams"})
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ArrayList<KeyPairBoolData> selectedSamplingData = new ArrayList<>();


            final AuditDataGetterSetter checkList = (AuditDataGetterSetter) getChild(groupPosition, childPosition);
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.audit_question_list_item, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.data = checkList;
            holder.txt_question.setText(holder.data.getQUESTION());
            holder.txt_question.setId(childPosition);

            final ArrayList<AuditDataGetterSetter> ans_list = hashMapAnsListChildData.get(holder.data);

            if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Single selection")) {
                holder.sp_auditAnswer.setVisibility(View.VISIBLE);
                holder.edt_answer.setVisibility(View.GONE);
                holder.relay_multisppener.setVisibility(View.GONE);
            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Multi selection")) {
                holder.edt_answer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.relay_multisppener.setVisibility(View.VISIBLE);
            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Text")) {
                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.relay_multisppener.setVisibility(View.GONE);
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_TEXT);
                holder.edt_answer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Number")) {
                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.relay_multisppener.setVisibility(View.GONE);
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER);
                holder.edt_answer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Decimal")) {
                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.relay_multisppener.setVisibility(View.GONE);
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                holder.edt_answer.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(6, 1)});

            }

            assert ans_list != null;
            if (!ans_list.isEmpty()) {
                holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_audit_item, ans_list));
                holder.sp_auditAnswer.setId(childPosition);
            }

            final ViewHolder finalHolder = holder;
            holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position != 0) {
                        AuditDataGetterSetter ans = ans_list.get(position);
                        finalHolder.data.setANSWER_ID(ans.getANSWER_ID());
                        finalHolder.data.setANSWER(ans.getANSWER());
                        finalHolder.data.setCAMERA_ALLOW(ans.getCAMERA_ALLOW());
                        if (finalHolder.data.getCAMERA_ALLOW().equals("1")) {
                            finalHolder.parent_cam_layout.setVisibility(View.VISIBLE);
                            finalHolder.parent_cam_layout.setId(childPosition);
                        } else {
                            finalHolder.parent_cam_layout.setVisibility(View.GONE);
                            finalHolder.parent_cam_layout.setId(childPosition);

                            if (finalHolder.data.getCAM_IMAGE() != null && finalHolder.data.getCAM_IMAGE().isEmpty()) {
                                if (new File(str + finalHolder.data.getCAM_IMAGE()).exists()) {
                                    new File(str + finalHolder.data.getCAM_IMAGE()).delete();
                                }
                            }
                            finalHolder.data.setCAM_IMAGE("");
                            finalHolder.img_cam.setBackgroundResource(R.mipmap.camera);
                            finalHolder.img_cam.setId(childPosition);
                        }

                        if (ans.getANSWER().equalsIgnoreCase("Others")) {
                            finalHolder.edt_for_others.setVisibility(View.VISIBLE);
                            finalHolder.edt_for_others.setId(childPosition);
                        } else {
                            finalHolder.data.setSpin_others_for_edt("");
                            finalHolder.edt_for_others.setText("");
                            finalHolder.edt_for_others.setVisibility(View.GONE);
                            finalHolder.edt_for_others.setId(childPosition);

                        }
                    } else {
                        finalHolder.data.setANSWER_ID("0");
                        finalHolder.data.setANSWER("");
                        finalHolder.data.setSpin_others_for_edt("");
                        finalHolder.edt_for_others.setText("");
                        finalHolder.edt_for_others.setId(childPosition);
                        finalHolder.img_cam.setBackgroundResource(R.mipmap.camera);
                        finalHolder.img_cam.setId(childPosition);
                        finalHolder.parent_cam_layout.setVisibility(View.GONE);
                        finalHolder.parent_cam_layout.setId(childPosition);
                        finalHolder.edt_for_others.setVisibility(View.GONE);
                        finalHolder.edt_for_others.setId(childPosition);
                    }
                }

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

                }
            });


            List<KeyPairBoolData> listArray0 = new ArrayList<>();
            if (!checkList.getSelectedSamplingData().isEmpty()) {
                selectedSamplingData.clear();
                listArray0.addAll(checkList.getSelectedSamplingData());
                holder.tv_mer.setVisibility(View.GONE);
            } else {
                for (int i = 0; i < ans_list.size(); i++) {
                    KeyPairBoolData h = new KeyPairBoolData();
                    h.setId(i + 1);
                    merCd = getEmp_idFromName(ans_list, ans_list.get(i).getANSWER());
                    h.setName(ans_list.get(i).getANSWER());
                    h.setMerCd(merCd);
                    h.setSelected(false);
                    listArray0.add(h);
                    holder.tv_mer.setVisibility(View.GONE);

                }
            }


            holder.searchSpinner.setOnTouchListener((view, motionEvent) -> {
                multitouch = true;
                return false;
            });

            final ArrayList<KeyPairBoolData> finalSelectedSamplingData = selectedSamplingData;
            final ViewHolder finalHolder2 = holder;

            holder.searchSpinner.setItemsProduct(listArray0, -1, items -> {
                if (multitouch) {
                    multitouch = false;
                    finalSelectedSamplingData.clear();
                    for (int i = 0; i < items.size(); i++) {
                        KeyPairBoolData h1 = new KeyPairBoolData();
                        h1.setAnswerCd(items.get(i).getAnswerCd());
                        h1.setName(items.get(i).getName());
                        h1.setSelected(items.get(i).isSelected());
                        finalSelectedSamplingData.add(h1);
                        Log.i("MultiSpinner", i + " : " + items.get(i).getAnswer() + " : " + items.get(i).isSelected());
                    }

                    if (!finalSelectedSamplingData.isEmpty()) {
                        boolean selectedData = false;
                        for (int i = 0; i < finalSelectedSamplingData.size(); i++) {
                            if (finalSelectedSamplingData.get(i).isSelected()) {
                                selectedData = true;
                                break;
                            }
                        }
                        finalHolder2.tv_mer.setVisibility(View.GONE);
                        finalHolder2.tv_mer.setId(childPosition);
                    } else {
                        finalHolder2.tv_mer.setVisibility(View.GONE);
                        finalHolder2.tv_mer.setId(childPosition);
                    }
                    checkList.setSelectedSamplingData(finalSelectedSamplingData);
                    adapter.notifyDataSetChanged();
                }
            });


            holder.img_cam.setOnClickListener(v -> {
                pathforcheck = counterId + "_ba_AuditPic_" + visitdate.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + pathforcheck;
                CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
                child_position = childPosition;
            });

            final ViewHolder finalHolder1 = holder;
            holder.edt_answer.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    finalHolder1.data.setANSWER_ID("0");
                    finalHolder1.data.setANSWER(((EditText) v).getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", ""));

                }
            });


            holder.edt_for_others.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    finalHolder1.data.setSpin_others_for_edt(CommonFunctions.removed_special_char((EditText) v));
                }
            });

            if ((holder.data.getANSWER_TYPE().equalsIgnoreCase("Single selection"))) {
                if (!ans_list.isEmpty()) {
                    for (int i = 0; i < ans_list.size(); i++) {
                        if (ans_list.get(i).getANSWER_ID().equals(holder.data.getANSWER_ID())) {
                            holder.sp_auditAnswer.setSelection(i);
                            break;
                        }
                    }
                }


                holder.edt_for_others.setText(holder.data.getSpin_others_for_edt());
                holder.edt_for_others.setId(childPosition);


            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Number") || holder.data.getANSWER_TYPE().equalsIgnoreCase("Decimal") || holder.data.getANSWER_TYPE().equalsIgnoreCase("Text")) {

                holder.edt_answer.setText(holder.data.getANSWER());
                holder.edt_answer.setId(childPosition);
            }

            if (!img_str.isEmpty()) {
                if (child_position == childPosition) {
                    holder.data.setCAM_IMAGE(img_str);
                    img_str = "";
                    child_position = -1;
                }
            }

            if (holder.data.getCAM_IMAGE().isEmpty()) {
                holder.img_cam.setBackgroundResource(R.mipmap.camera);
                holder.img_cam.setId(childPosition);
            } else {
                holder.img_cam.setBackgroundResource(R.mipmap.camera_tick);
                holder.img_cam.setId(childPosition);
            }

            if (!checkflag) {
                if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) {
                    holder.card_view.setBackgroundColor(ContextCompat.getColor(_context, R.color.red));
                    holder.card_view.setId(childPosition);
                } else {
                    holder.card_view.setBackgroundColor(ContextCompat.getColor(_context, R.color.white));
                    holder.card_view.setId(childPosition);
                }
            }


            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return this.listDataHeader.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return this.listDataHeader.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_header_expandable_window, parent, false);
            }

            final MasterProfileQuestion headerTitle = (MasterProfileQuestion) getGroup(groupPosition);
            TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header);
            CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists);
            lblListHeader.setText(headerTitle.getCategory());

            cardView.setOnClickListener(v -> {
                if (expandableListView.isGroupExpanded(groupPosition)) {
                    expandableListView.collapseGroup(groupPosition);
                } else {
                    expandableListView.expandGroup(groupPosition);
                }
            });

            if (!checkflag) {
                if (checkGroupArray.contains(groupPosition)) {
                    cardView.setBackgroundColor(ContextCompat.getColor(_context, R.color.red));
                } else {
                    cardView.setBackgroundColor(ContextCompat.getColor(_context, R.color.colorPrimaryDark));
                }
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView txt_question;
            public final Spinner sp_auditAnswer;
            public final EditText edt_answer, edt_for_others;
            public final ImageView img_cam;
            public final RelativeLayout parent_cam_layout;
            CardView card_view;
            public final RelativeLayout relay_multisppener;
            BaProfileMultiSelection searchSpinner;
            public final TextView tv_mer;
            AuditDataGetterSetter data;

            public ViewHolder(View view) {
                super(view);
                mView = view;
                tv_mer = (TextView) view.findViewById(R.id.tv_mer);
                txt_question = (TextView) view.findViewById(R.id.txt_question);
                sp_auditAnswer = (Spinner) view.findViewById(R.id.sp_auditAnswer);
                card_view = (CardView) view.findViewById(R.id.card_view);
                edt_answer = (EditText) view.findViewById(R.id.edt_answer);
                edt_for_others = (EditText) view.findViewById(R.id.edt_for_others);
                img_cam = (ImageView) view.findViewById(R.id.img_cam);
                parent_cam_layout = (RelativeLayout) view.findViewById(R.id.parent_cam_layout);
                relay_multisppener = (RelativeLayout) view.findViewById(R.id.relay_multisppener);
                searchSpinner = (BaProfileMultiSelection) view.findViewById(R.id.searchSpinner);
            }
        }

    }


    public static class AnswerSpinnerAdapter extends ArrayAdapter<AuditDataGetterSetter> {
        List<AuditDataGetterSetter> list;
        Context context;
        int resourceId;

        public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList<AuditDataGetterSetter> list) {
            super(context, resourceId, list);
            this.context = context;
            this.list = list;
            this.resourceId = resourceId;
        }

        @NonNull
        @SuppressLint("ViewHolder")
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            AuditDataGetterSetter cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text);
            txt_spinner.setText(list.get(position).getANSWER());

            return view;
        }

        @Override
        public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            AuditDataGetterSetter cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text);
            txt_spinner.setText(cm.getANSWER());
            return view;
        }
    }

    boolean validateData(ArrayList<MasterProfileQuestion> listDataHeader, HashMap<MasterProfileQuestion, ArrayList<AuditDataGetterSetter>> listDataChild) {
        checkHeaderArray.clear();
        checkGroupArray.clear();
        loop:
        for (int j = 0; j < listDataHeader.size(); j++) {
            ArrayList<AuditDataGetterSetter> data = listDataChild.get(listDataHeader.get(j));
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("Text") || data.get(i).getANSWER_TYPE().equalsIgnoreCase("Number") || data.get(i).getANSWER_TYPE().equalsIgnoreCase("Decimal")) {
                    if (data.get(i).getANSWER() == null || data.get(i).getANSWER().equalsIgnoreCase("")) {
                        error_msg = getString(R.string.pls_answer_all_qns);
                        checkflag = false;
                    } else {
                        checkflag = true;
                    }
                } else if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("Single selection")) {
                    if (data.get(i).getANSWER_ID().equalsIgnoreCase("0")) {
                        error_msg = getString(R.string.pls_answer_all_qns);
                        checkflag = false;
                    } else if (data.get(i).getCAMERA_ALLOW().equals("1") && data.get(i).getCAM_IMAGE().isEmpty()) {
                        error_msg = getString(R.string.click_image);
                        checkflag = false;
                    } else {
                        checkflag = true;
                    }
                } else if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("Multi selection")) {
                    if (!data.get(i).getSelectedSamplingData().isEmpty()) {
                        checkflag = false;
                        for (int k = 0; k < data.get(i).getSelectedSamplingData().size(); k++) {
                            if (data.get(i).getSelectedSamplingData().get(k).isSelected()) {
                                checkflag = true;
                            }
                        }
                        if (!checkflag) {
                            error_msg = ("Please select atleast one checklist answer");
                        }
                    } else {
                        checkflag = false;
                        error_msg = ("Please select atleast one checklist answer");
                    }
                }

                if (!checkflag) {
                    if (!checkHeaderArray.contains(i)) {
                        checkHeaderArray.add(i);
                        checkGroupArray.add(j);
                    }
                    break loop;
                }
            }
        }


        return checkflag;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("MakeMachine", "resultCode: " + resultCode);
        switch (resultCode) {
            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;
            case -1:
                if (pathforcheck != null && !pathforcheck.isEmpty()) {
                    if (new File(CommonString.getImagesFolder(context) + pathforcheck).exists()) {
                        deleteexistingfile();
                        try {
                            Bitmap bmp = convertBitmap(CommonString.getImagesFolder(context) + pathforcheck);
                            round_img_pic.setImageBitmap(bmp);
                        } catch (OutOfMemoryError ex) {
                            CommonFunctions.setScaledImage(round_img_pic, CommonString.getImagesFolder(context) + pathforcheck);
                        }

                        round_img_pic.setVisibility(View.VISIBLE);
                        img_str = pathforcheck;
                        baProfileGetterSetter.setProfilePic(img_str);
                        copyFile(pathforcheck);
                        pathforcheck = "";
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void copyFile(String file_name) {
        try {
            // the file to be moved or copied
            File sourceLocation = new File(CommonString.getImagesFolder(context) + file_name);
            // make sure your target location folder exists!
            File targetLocation = new File(CommonString.getProfileFolder(context), file_name);
            // make sure the target file exists
            if (sourceLocation.exists()) {
                InputStream in = new FileInputStream(sourceLocation);
                OutputStream out = new FileOutputStream(targetLocation);
                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
                Log.v("", "Copy file successful.");
            } else {
                Log.v("", "Copy file failed. Source file missing.");
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private class DecimalDigitsInputFilter implements InputFilter {
        Pattern mPattern;

        private DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
            mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher matcher = mPattern.matcher(dest);
            if (!matcher.matches()) return "";
            return null;
        }

    }

    String getEmp_idFromName(ArrayList<AuditDataGetterSetter> finalAns_list, String name) {
        String emp_cd = "0";
        for (int i = 0; i < finalAns_list.size(); i++) {
            if (finalAns_list.get(i).getANSWER().equalsIgnoreCase(name)) {
                emp_cd = String.valueOf(finalAns_list.get(i).getANSWER_ID());
                break;
            }
        }

        return emp_cd;
    }


    private boolean validateimg_str() {
        boolean status = true;
        if (baProfileGetterSetter.getProfilePic() == null && !baProfileListData.isEmpty() && baProfileListData.get(0).getProfilePic().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Click Profile Imge");
            status = false;
        } else if (edt_mobile_no.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Enter Mobile Number");
            status = false;
        } else if (edt_mobile_no.getText().toString().length() < 10) {
            AlertandMessages.showToastMsg(context, "Please Enter Atleast 10 Digit Contact Number ");
            status = false;
        } else if (storeProfile_dob.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Tab To Select DOB");
            status = false;
        } else if (edt_address.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Enter Address");
            status = false;
        } else if (edt_landmark.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Enter Landmark");
            status = false;
        } else if (edt_location.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Enter Location");
            status = false;
        } else if (edt_email.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Enter Email Address");
            status = false;
        } else if (!edt_email.getText().toString().isEmpty() && !CommonFunctions.isValidEmail(edt_email.getText().toString())) {
            AlertandMessages.showToastMsg(context, "Please Enter Valid Email Id ");
            status = false;
        }

        return status;
    }

    @SuppressLint("SetTextI18n")
    private void validate() {
        update_flag = false;
        db.open();
        storelist = db.getStoreData(visitdate, user_name, counterId);
        baProfileGetterSetter = db.getBaProfileData(user_name, visitdate, false);
        baProfileListData = db.getBAProfileListAllData(user_name, visitdate);

        if (!storelist.isEmpty()) {
            edt_brand.setText(storelist.get(0).getStoreTypeName());
            edt_counter.setText(storelist.get(0).getClassId().toString());
            edt_store_name.setText(storelist.get(0).getStoreName());
            edt_location.setText(storelist.get(0).getLocation());
            edt_city.setText(storelist.get(0).getCityName());
            edt_landmark.setText(storelist.get(0).getLandmark());
        }


        if (!baProfileListData.isEmpty()) {
            profile_user.setText(baProfileListData.get(0).getFullName());
            if (user_type != null && !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)) {
                profile_user_type.setText("Beauty Advisor");
            } else if (user_type != null && !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {
                profile_user_type.setText("Temp Beauty Advisor");
            } else if (user_type != null && !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                profile_user_type.setText("Makeup Expert");
            }

            edt_enstagram_address.setText(baProfileListData.get(0).getInstragramAddress());
            edt_email.setText(baProfileListData.get(0).getEmail());
            edt_mobile_no.setText(baProfileListData.get(0).getMobile());
            storeProfile_dob.setText(baProfileListData.get(0).getDob());
            edt_address.setText(baProfileListData.get(0).getAddress());
            edt_employee_code.setText(baProfileListData.get(0).getEmpCode());
            edt_full_name.setText(baProfileListData.get(0).getFullName());
            supervisor_name.setText(baProfileListData.get(0).getSupervisor());
            edt_current_bp.setText(baProfileListData.get(0).getCurrentBPgrade());
            /////for radio group
            if (baProfileListData.get(0).getGender().equalsIgnoreCase("Male")) {
                //radioSexButton
                radioSexGroup.check(R.id.radioM);
            } else if (baProfileListData.get(0).getGender().equalsIgnoreCase("Female")) {
                //radioSexButton
                radioSexGroup.check(R.id.radioF);
            } else {
                radioSexGroup.check(R.id.radio_other);
            }
        }


        if (baProfileGetterSetter != null && baProfileGetterSetter.getUserId() != null && !baProfileGetterSetter.getUserId().isEmpty()) {
            fab.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.edit));
            edt_address.setText(baProfileGetterSetter.getAddress() != null ? baProfileGetterSetter.getAddress() : "");
            edt_location.setText(baProfileGetterSetter.getLocation() != null ? baProfileGetterSetter.getLocation() : "");
            edt_landmark.setText(baProfileGetterSetter.getLandmark() != null ? baProfileGetterSetter.getLandmark() : "");
            storeProfile_dob.setText(baProfileGetterSetter.getDob() != null ? baProfileGetterSetter.getDob() : "");
            edt_mobile_no.setEnabled(baProfileGetterSetter.getMobile() != null);
            edt_mobile_no.setText(baProfileGetterSetter.getMobile() != null ? baProfileGetterSetter.getMobile() : "");
            edt_email.setText(baProfileGetterSetter.getEmail() != null ? baProfileGetterSetter.getEmail() : "");
            edt_enstagram_address.setText(baProfileGetterSetter.getInstragramAddress() != null ? baProfileGetterSetter.getInstragramAddress() : "");
            pathforcheck = baProfileGetterSetter.getProfilePic() != null ? baProfileGetterSetter.getProfilePic() : "";
        }

        assert baProfileGetterSetter != null;
        if (baProfileGetterSetter.getProfilePic() != null && !baProfileGetterSetter.getProfilePic().isEmpty()) {
            if (new File(CommonString.getProfileFolder(context) + pathforcheck).exists()) {
                Bitmap bitmp = convertBitmap(CommonString.getProfileFolder(context) + baProfileGetterSetter.getProfilePic());
                assert bitmp != null;
                round_img_pic.setImageBitmap(bitmp);
            } else {
                bitmp = BitmapFactory.decodeResource(getResources(), R.mipmap.profile_image);
                round_img_pic.setImageBitmap(bitmp);
            }
        } else if (!baProfileListData.isEmpty() && baProfileListData.get(0).getProfilePic() != null && !baProfileListData.get(0).getProfilePic().isEmpty()) {
            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);
        }
    }
}
