package com.cpm.lorealbaMabeline.makeupexpert;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

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

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.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.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.download.Downloader;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MEMEAuditQuestion;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MEQuizActivity extends AppCompatActivity implements View.OnClickListener {
    String error_msg = "", pathforcheck = "", _path = "", str, img_str = "", visit_date, username, counter_Id;
    HashMap<MEMEAuditQuestion, ArrayList<MEMEAuditQuestion>> listDataChild;
    ArrayList<MEMEAuditQuestion> question_list;
    List<Integer> checkHeaderArray = new ArrayList<>();
    List<Integer> checkGroupArray = new ArrayList<>();
    ArrayList<MEMEAuditQuestion> listDataHeader;
    boolean checkflag = true, multitouch = false, Singletouch = false, update_flag = false;
    SharedPreferences preferences;
    ExpandableListView expandableListView;
    ExpandableListAdapter adapter;
    FloatingActionButton fab;
    private static int child_position = -1, group_position = -1;
    MEMEAuditQuestion obj = null;
    Lorealba_Database db;
    Toolbar toolbar;
    Context context;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       preferences = PrefHelper.getPrefs(context);
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        obj = (MEMEAuditQuestion) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        if (obj != null) {
            setTitle(obj.getQuizName().trim() + " - " + username);
        }
        str = CommonString.getImagesFolder(context);
        expandableListView = (ExpandableListView) findViewById(R.id.list);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);
        validate_ui_data();
    }

    private void validate_ui_data() {
        //Header
        db.open();
        listDataHeader = db.getAuditQuestionCategoryDataNew(obj.getQuizId().toString());
        question_list = new ArrayList<>();
        listDataChild = new HashMap<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            db.open();
            question_list = db.getme_quiz_from_database(listDataHeader.get(i).getCategoryId().toString(), username, visit_date, counter_Id, obj.getQuizId().toString());
            if (question_list.size() == 0) {
                question_list = db.getAuditCategoryWiseDataNew(listDataHeader.get(i).getCategoryId(), obj.getQuizId().toString());
            } else {
                update_flag = true;
                fab.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.edit));
            }
            ArrayList<MEMEAuditQuestion> list = new ArrayList<>();
            if (question_list.size() > 0) {
                String select = getString(R.string.title_activity_select_dropdown);
                // Adding child data
                for (int j = 0; j < question_list.size(); j++) {
                    question_list.get(j).setAnswerList(db.getAuditAnswerDataNew(question_list.get(j), select));
                    list.add(question_list.get(j));
                }
            }
            listDataChild.put(listDataHeader.get(i), list);
        }

        adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        expandableListView.setAdapter(adapter);

        for (int i = 0; i < adapter.getGroupCount(); i++) {
            expandableListView.expandGroup(i);
        }

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

    @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 (checkflag) {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                MEQuizActivity.this.finish();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                        .setPositiveButton(getString(R.string.ok), (dialog, id1) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            MEQuizActivity.this.finish();
                        }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
                AlertDialog alert = builder.create();
                alert.show();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (checkflag) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            MEQuizActivity.this.finish();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).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);
                        MEQuizActivity.this.finish();
                    }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
            AlertDialog alert = builder.create();
            alert.show();
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.fab) {
            expandableListView.clearFocus();
            expandableListView.invalidateViews();
            if (validateData(listDataHeader, listDataChild)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_Want_save)
                        .setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> {
                            db.open();
                            db.insert_me_quiz_data(counter_Id, visit_date, username, listDataHeader, listDataChild, obj, CommonFunctions.getUUID(context));
                            //download service
                            Intent intent = new Intent(context, Downloader.class);
                            intent.putExtra(CommonString.KEY_ME_QUIZ, listDataHeader);
                            Downloader.enqueueWork(context, intent);

                            AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            MEQuizActivity.this.finish();
                            dialog.dismiss();
                        }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                AlertandMessages.showToastMsg(context, error_msg);
            }
        }

    }


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

        public ExpandableListAdapter(Context context, ArrayList<MEMEAuditQuestion> listDataHeader, HashMap<MEMEAuditQuestion, ArrayList<MEMEAuditQuestion>> 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"})
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            final MEMEAuditQuestion checkList = (MEMEAuditQuestion) getChild(groupPosition, childPosition);
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.quiz_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<MEMEAuditQuestion> ans_list = (holder.data).getAnswerList();

            if (holder.data.getQuestionType().equalsIgnoreCase("List Single Choice")) {
                holder.sp_auditAnswer.setVisibility(View.VISIBLE);
                holder.sp_auditAnswer.setId(childPosition);

                holder.edt_answer.setVisibility(View.GONE);
                holder.edt_answer.setId(childPosition);

                holder.relay_multisppener.setVisibility(View.GONE);
                holder.relay_multisppener.setId(childPosition);

            } else if (holder.data.getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(childPosition);

                holder.edt_answer.setVisibility(View.GONE);
                holder.edt_answer.setId(childPosition);

                holder.relay_multisppener.setVisibility(View.VISIBLE);
                holder.relay_multisppener.setId(childPosition);
            } else if (holder.data.getQuestionType().equalsIgnoreCase("Text")) {
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(childPosition);

                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.edt_answer.setId(childPosition);

                holder.relay_multisppener.setVisibility(View.GONE);
                holder.relay_multisppener.setId(childPosition);
            } else if (holder.data.getQuestionType().equalsIgnoreCase("Number")) {
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(childPosition);

                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.edt_answer.setId(childPosition);

                holder.relay_multisppener.setVisibility(View.GONE);
                holder.relay_multisppener.setId(childPosition);

                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER);
                holder.edt_answer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});


            } else if (holder.data.getQuestionType().equalsIgnoreCase("Decimal")) {
                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(childPosition);

                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.edt_answer.setId(childPosition);

                holder.relay_multisppener.setVisibility(View.GONE);
                holder.relay_multisppener.setId(childPosition);
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                holder.edt_answer.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(10, 1)});

            }

            if (ans_list.size() > 0) {
                holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_audit_item, ans_list));
                holder.sp_auditAnswer.setId(childPosition);
            }

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


            final ArrayList<MEMEAuditQuestion> finalAns_list = ans_list;
            final ViewHolder finalHolder = holder;
            holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (Singletouch) {
                        if (position != 0) {
                            MEMEAuditQuestion ans = finalAns_list.get(position);
                            finalHolder.data.setAnswerId(ans.getAnswerId());
                            finalHolder.data.setAnswer(ans.getAnswer());
                            finalHolder.data.setImageAllow(ans.getImageAllow());
                            if (finalHolder.data.getImageAllow()) {
                                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.getStr_audit_img().equals("")) {
                                    if (new File(str + finalHolder.data.getStr_audit_img()).exists()) {
                                        new File(str + finalHolder.data.getStr_audit_img()).delete();
                                    }
                                }
                                finalHolder.data.setStr_audit_img("");
                                finalHolder.img_cam.setImageResource(R.mipmap.camera_bs);
                                finalHolder.img_cam.setId(childPosition);
                            }
                        } else {
                            if ((finalHolder.data.getQuestionType().equalsIgnoreCase("List Single Choice"))) {
                                finalHolder.data.setAnswerId(0);
                                finalHolder.data.setAnswer("");
                            }
                        }
                    }
                    Singletouch = false;
                }

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

                }
            });


            holder.img_cam.setOnClickListener(v -> {
                child_position = childPosition;
                group_position = groupPosition;
                pathforcheck = counter_Id + username + "_" + checkList.getQuestionId().toString() + "_QuizPic-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTime_only().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + pathforcheck;
                CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
            });


            holder.edt_answer.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    final EditText Caption = (EditText) v;
                    String value1 = Caption.getText().toString();
                    if (!value1.equals("")) {
                        finalHolder.data.setAnswer(value1);
                    } else {
                        finalHolder.data.setAnswer("");
                    }
                }
            });

            holder.edt_answer.setText(holder.data.getAnswer());
            holder.edt_answer.setId(childPosition);

            if ((holder.data.getQuestionType().equalsIgnoreCase("List Single Choice"))) {
                if (ans_list.size() > 0) {
                    for (int i = 0; i < ans_list.size(); i++) {
                        if (ans_list.get(i).getAnswerId().toString().equals(holder.data.getAnswerId().toString())) {
                            holder.sp_auditAnswer.setSelection(i);
                            break;
                        }

                    }
                }
            } else if (holder.data.getQuestionType().equalsIgnoreCase("Number") || holder.data.getQuestionType().equalsIgnoreCase("Decimal") || holder.data.getQuestionType().equalsIgnoreCase("Text")) {
                holder.edt_answer.setText(holder.data.getAnswer());
                holder.edt_answer.setId(childPosition);
            }


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

            if (update_flag) {
                if (holder.data.getQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                    for (int k3 = 0; k3 < holder.data.getAnswerList().size(); k3++) {
                        if (db.ischeckedgetquiz_answer(holder.data.getKeyId(), username, holder.data.getAnswerList().get(k3).getAnswerId().toString())) {
                            holder.data.getAnswerList().get(k3).setSelected(true);
                        }
                    }
                }
            }

            holder.searchSpinner.setItemsProduct(holder.data.getAnswerList(), -1, items -> {
                if (multitouch) {
                    for (int i = 0; i < items.size(); i++) {
                        if (items.get(i).isSelected()) {

                        }
                    }
                }

                multitouch = false;

            });

            if (!img_str.equals("")) {
                if (group_position == groupPosition) {
                    if (child_position == childPosition) {
                        holder.data.setStr_audit_img(img_str);
                        img_str = "";
                    }

                }
            }


            if (!holder.data.getStr_audit_img().equals("")) {
                holder.img_cam.setImageResource(R.mipmap.camera_bsd);
                holder.img_cam.setId(childPosition);
            } else {
                holder.img_cam.setImageResource(R.mipmap.camera_bs);
                holder.img_cam.setId(childPosition);
            }

            if (holder.data.getImageAllow()) {
                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 (!checkflag) {
                if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) {
                    holder.card_view.setBackgroundColor(getResources().getColor(R.color.red));
                    holder.card_view.setId(childPosition);
                } else {
                    holder.card_view.setBackgroundColor(getResources().getColor(R.color.white));
                    holder.card_view.setId(childPosition);
                }
            } else {
                holder.card_view.setBackgroundColor(getResources().getColor(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 MEMEAuditQuestion headerTitle = (MEMEAuditQuestion) 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(getResources().getColor(R.color.red));
                } else {
                    cardView.setBackgroundColor(getResources().getColor(R.color.bright_red));
                }
            } else {
                cardView.setBackgroundColor(getResources().getColor(R.color.bright_red));
            }

            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;
            public final ImageView img_cam;
            public final RelativeLayout parent_cam_layout;
            CardView card_view;
            MEMEAuditQuestion data;
            public final RelativeLayout relay_multisppener;
            MultiselectionCategorySpinnerSearch searchSpinner;

            public ViewHolder(View view) {
                super(view);
                mView = view;
                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);
                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 = (MultiselectionCategorySpinnerSearch) view.findViewById(R.id.multispin_search);
            }
        }
    }

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            MEMEAuditQuestion 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, ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);

            MEMEAuditQuestion cm = list.get(position);

            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_text);
            txt_spinner.setText(cm.getAnswer());

            return view;
        }
    }

    boolean validateData(ArrayList<MEMEAuditQuestion> listDataHeader, HashMap<MEMEAuditQuestion, ArrayList<MEMEAuditQuestion>> listDataChild) {
        checkHeaderArray.clear();
        checkGroupArray.clear();
        checkflag = true;
        for (int j = 0; j < listDataHeader.size(); j++) {
            ArrayList<MEMEAuditQuestion> data = listDataChild.get(listDataHeader.get(j));
            assert data != null;
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getQuestionType().equalsIgnoreCase("List Single Choice")
                        && !data.get(i).getAnswerId().toString().equals("0") &&
                        data.get(i).getImageAllow()
                        && data.get(i).getStr_audit_img().equals("")) {
                    error_msg = getString(R.string.pls_click_image);
                    checkflag = false;
                    break;
                } else if (data.get(i).getQuestionType().equalsIgnoreCase("List Single Choice")
                        && data.get(i).getAnswerId().toString().equals("0")) {
                    error_msg = getString(R.string.pls_answer_all_qns);
                    checkflag = false;
                    break;
                } else if (data.get(i).getQuestionType().equalsIgnoreCase("Text")
                        || data.get(i).getQuestionType().equalsIgnoreCase("Number") ||
                        data.get(i).getQuestionType().equalsIgnoreCase("Decimal")) {
                    if (data.get(i).getAnswer().equals("")) {
                        error_msg = getString(R.string.pls_answer_all_qns);
                        checkflag = false;
                        break;
                    }
                } else if (data.get(i).getQuestionType().equalsIgnoreCase("List Multiple Choice") && data.get(i).getAnswerList().size() > 0 && !check(data.get(i).getAnswerList())) {
                    error_msg = getString(R.string.pls_answer_all_qns);
                    checkflag = false;
                    break;
                }

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

        return checkflag;
    }


    private boolean check(ArrayList<MEMEAuditQuestion> answerList) {
        boolean flag = true;
        if (answerList.size() > 0) {
            for (int k = 0; k < answerList.size(); k++) {
                if (!answerList.get(k).isSelected()) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    @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.equals("")) {
                    if (new File(str + pathforcheck).exists()) {
                        img_str = pathforcheck;
                        pathforcheck = "";
                        adapter.notifyDataSetChanged();
                    }
                }

        }
    }

    public class DecimalDigitsInputFilter implements InputFilter {
        Pattern mPattern;
        public 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;
        }

    }


}
