package com.cpm.lorealbaMabeline.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;

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

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

import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
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.ProgressBar;
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.gsonGetterSetter.BASurveyGetterSetter;
import com.cpm.lorealbaMabeline.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterSurvey;
import com.cpm.lorealbaMabeline.retrofit.PostApi;

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

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

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

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


public class BASurveyActivity extends AppCompatActivity {
    List<Integer> checkHeaderArray = new ArrayList<>();
    List<Integer> checkGroupArray = new ArrayList<>();
    boolean checkflag = true;
    SharedPreferences preferences;
    String pathforcheck = "", _path = "", str, img_str = "", counter_id = "", surveyId = "", surveyType = ""; //img_str2 = "";
    String visit_date, username;
    Lorealba_Database db;
    ArrayList<BASurveyGetterSetter> question_list, childListData;
    HashMap<BASurveyGetterSetter, ArrayList<BASurveyGetterSetter>> hashMapAnsListChildData;
    int child_position = -1;
    String error_msg = "";
    Toolbar toolbar;
    Context context;
    FloatingActionButton fab;
    ExpandableListView expandableListView;
    ExpandableListAdapter adapter;
    ArrayList<MasterSurvey> listDataHeader;
    ArrayList<BASurveyGetterSetter> listChildData;
    HashMap<MasterSurvey, ArrayList<BASurveyGetterSetter>> listDataChild;
    JourneyPlan jcp_Object = new JourneyPlan();
    ArrayList<BASurveyGetterSetter> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ba_survey);
        context = this;
        //Intent data
        if (getIntent().getStringExtra("SurveyId") != null && getIntent().getStringExtra("SurveyType") != null) {
            surveyId = getIntent().getStringExtra("SurveyId");
            surveyType = getIntent().getStringExtra("SurveyType");
        }

        preferences = PrefHelper.getPrefs(this);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        if (surveyType.equalsIgnoreCase("BA")) {
            setTitle("BA Survey - " + username);
        } else {
            setTitle("Counter Survey - " + visit_date);
        }

        str = CommonString.getImagesFolder(context);
        expandableListView = (ExpandableListView) findViewById(R.id.list);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                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();
                }
            }
        });

        db = new Lorealba_Database(context);
        db.open();
        jcp_Object = db.getBIDfromJCP(username, counter_id);
        //Header
        question_list = new ArrayList<>();
        listDataChild = new HashMap<>();
        if (surveyType.equalsIgnoreCase("BA")) {
            db.open();
            listDataHeader = db.getSurveyData("BA", surveyId);
        } else {
            db.open();
            listDataHeader = db.getSurveyData("Counter", surveyId);
        }

        for (int i = 0; i < listDataHeader.size(); i++) {
            // Adding child data
            db.open();
            question_list = db.getSurveyWiseData(listDataHeader.get(i).getSurveyId());
            if (!question_list.isEmpty()) {
                String select = getString(R.string.title_activity_select_dropdown);
                for (int j = 0; j < question_list.size(); j++) {
                    // Adding answer list data
                    db.open();
                    childListData = db.getSurveyAnswerData(question_list.get(j), select);
                    question_list.get(j).setAnswerList(childListData);
                }
            }

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

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

        fab.setOnClickListener(view -> {
            expandableListView.clearFocus();
            if (validateData(listDataHeader, listDataChild)) {
                if (CommonFunctions.checkNetIsAvailable(context)) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.ba_survey_save_data_msg)
                            .setCancelable(false)
                            .setPositiveButton(R.string.yes, (dialog, id) -> {
                                db.open();
                                if (db.saveBASurveyAnswerData(listDataHeader, listDataChild, counter_id, visit_date, jcp_Object, surveyType) > 0) {
                                    if (CommonFunctions.checkNetIsAvailable(context)) {
                                        new InsertAsync().execute(false);
                                    }
                                } else {
                                    AlertandMessages.showToastMsg(context, "Error in data saving");
                                }
                            }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel());

                    AlertDialog alert = builder.create();
                    alert.show();
                } else {
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            } else {
                AlertandMessages.showToastMsg(context, error_msg);
            }
        });
    }

    private Dialog dialog;
    ProgressBar pb;

    @SuppressLint("StaticFieldLeak")
    class InsertAsync extends AsyncTask<Boolean, Void, Void> {
        boolean flag = false;

        @Override
        protected void onPreExecute() {
            dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.setContentView(R.layout.circular_progress_bar);
            pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
            dialog.setCancelable(false);
            dialog.show();
            super.onPreExecute();
        }


        @Override
        protected Void doInBackground(Boolean... bool) {
            UploadStockRecursive(jcp_Object);
            return null;
        }


        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }


    private void UploadStockRecursive(JourneyPlan jcp) {
        try {
            JSONArray topUpArray = new JSONArray();
            String key = "";
            db.open();
            if (surveyType.equalsIgnoreCase("BA")) {
                key = "BASurveyData";
                listDataHeader = db.getBASurveySavedData("BA", jcp, visit_date);
            } else {
                key = "CounterSurveyData";
                listDataHeader = db.getBASurveySavedData("Counter", jcp, visit_date);
            }

            for (int j = 0; j < listDataHeader.size(); j++) {
                JSONObject obj = new JSONObject();
                obj.put("BID", jcp.getBID());
                obj.put("UserId", username);
                obj.put("CounterId", counter_id);
                obj.put("SurveyType", listDataHeader.get(j).getSurveyType());
                obj.put("SurveyId", listDataHeader.get(j).getSurveyId());
                db.open();
                listChildData = db.getChildData(surveyType, jcp, visit_date, listDataHeader.get(j).getCommon_id());

                for (int i = 0; i < listChildData.size(); i++) {
                    JSONObject obj1 = getJsonObject(jcp, i);
                    topUpArray.put(obj1);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", jcp.getMID());
            jsonObject.put("Keys", key);
            jsonObject.put("JsonData", topUpArray.toString());
            jsonObject.put("UserId", username);

            String jsonString = jsonObject.toString();

            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"), jsonString);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<ResponseBody> call = null;
            call = api.getUploadJsonDetail(jsonData);

            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                    ResponseBody responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            assert response.body() != null;
                            data = response.body().string();
                            if (data.equalsIgnoreCase("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.contains("Success")) {
                                    db.open();
                                    db.updateBASurveyData(surveyType, "1");
                                    dialog.cancel();
                                    finish();
                                }
                            }

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

                        }
                    } else {
                        dialog.cancel();
                        AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                    dialog.cancel();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE);
                }
            });


        } catch (JSONException e) {
            dialog.cancel();
            e.fillInStackTrace();
        }
    }

    private @NonNull JSONObject getJsonObject(JourneyPlan jcp, int i) throws JSONException {
        JSONObject obj1 = new JSONObject();
        if (surveyType.equalsIgnoreCase("BA")) {
            obj1.put("BID", jcp.getBID());
        } else {
            obj1.put("MID", jcp.getMID());
        }
        obj1.put("UserId", username);
        obj1.put("CounterId", counter_id);
        obj1.put("Visit_date", visit_date);
        obj1.put("SurveyId", listChildData.get(i).getSurveyId());
        obj1.put("SurveyQuestionId", listChildData.get(i).getSurveyQuestionId());
        if (listChildData.get(i).getCorrect_answer_id().equalsIgnoreCase("0")) {
            obj1.put("Survey_Correct_Answer_Id", "0");
        } else {
            obj1.put("Survey_Correct_Answer_Id", listChildData.get(i).getCorrect_answer_id());
        }

        obj1.put("Survey_Correct_Answer", listChildData.get(i).getSurveyAnswer());
        obj1.put("Survey_Image", listChildData.get(i).getCam_image());
        return obj1;
    }

    @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) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Parinaam");
            builder.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);
                        finish();
                    })
                    .setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
                        dialog.dismiss();
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Parinaam");
        builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                .setPositiveButton(getString(R.string.ok), (dialog, id) -> finish())
                .setNegativeButton(getString(R.string.cancel), (dialog, which) -> {

                });
        AlertDialog alert = builder.create();
        alert.show();
    }

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

        public ExpandableListAdapter(Context context, ArrayList<MasterSurvey> listDataHeader, HashMap<MasterSurvey, ArrayList<BASurveyGetterSetter>> 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", "InflateParams"})
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            BASurveyGetterSetter checkList = (BASurveyGetterSetter) 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.getSurveyQuestion());

            final ArrayList<BASurveyGetterSetter> ans_list = (holder.data).getAnswerList();

            if (holder.data.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") ||
                    holder.data.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice")) {
                holder.sp_auditAnswer.setVisibility(View.VISIBLE);
                holder.edt_answer.setVisibility(View.GONE);
            } else {
                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.sp_auditAnswer.setVisibility(View.GONE);
            }


            if (!ans_list.isEmpty()) {
                holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(context, R.layout.custom_spinner_item, 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 (position != 0) {
                        BASurveyGetterSetter ans = ans_list.get(position);
                        finalHolder.data.setCorrect_answer_id(ans.getSurveyAnswerId());
                        finalHolder.data.setSurveyAnswer(ans.getSurveyAnswer());
                        //finalHolder.data.setImageAllow(ans.getImageAllow());
                        if (finalHolder.data.getImageAllow().equals("1")) {
                            finalHolder.parent_cam_layout.setVisibility(View.VISIBLE);
                        } else {
                            finalHolder.parent_cam_layout.setVisibility(View.GONE);
                            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_bsd);
                        }
                    } else {
                        if ((finalHolder.data.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") ||
                                finalHolder.data.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice"))) {
                            finalHolder.data.setCorrect_answer_id("0");
                            finalHolder.data.setSurveyAnswer("");
                        }
                    }
                }

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

                }
            });

            holder.img_cam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (surveyType.equalsIgnoreCase("BA")) {
                        pathforcheck = jcp_Object.getBID() + "_" + counter_id + "_BASurveyPic-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg";
                    } else {
                        pathforcheck = jcp_Object.getMID() + "_" + counter_id + "_CounterSurveyPic-" + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeHHMMSS().replace(":", "") + ".jpg";
                    }
                    _path = CommonString.getImagesFolder(context) + pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
                    child_position = childPosition;
                    //startCameraActivity(0);
                }
            });


            if (holder.data.getSurveyQuestionType().equalsIgnoreCase("Number")) {
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER);
            } else if (holder.data.getSurveyQuestionType().equalsIgnoreCase("Decimal")) {
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else {
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_TEXT);
            }

            holder.edt_answer.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    finalHolder.data.setSurveyAnswerId("0");
                    finalHolder.data.setSurveyAnswer(((EditText) v).getText().toString());
                }
            });

            if (ans_list.size() > 0) {
                for (int i = 0; i < ans_list.size(); i++) {
                    if ((holder.data.getSurveyQuestionType().equalsIgnoreCase("List Single Choice") ||
                            holder.data.getSurveyQuestionType().equalsIgnoreCase("List Multiple Choice")) &&
                            ans_list.get(i).getSurveyAnswerId().equals(holder.data.getCorrect_answer_id())) {
                        holder.sp_auditAnswer.setSelection(i);
                        break;
                    }
                }
            }

            if (holder.data.getSurveyQuestionType().equalsIgnoreCase("Text") ||
                    holder.data.getSurveyQuestionType().equalsIgnoreCase("Decimal") ||
                    holder.data.getSurveyQuestionType().equalsIgnoreCase("Number")) {
                holder.edt_answer.setText(holder.data.getSurveyAnswer());
                holder.edt_answer.setId(childPosition);
            }

            if (holder.data.getImageAllow().equalsIgnoreCase("1")) {
                finalHolder.parent_cam_layout.setVisibility(View.VISIBLE);
                holder.img_cam.setVisibility(View.VISIBLE);
            } else {
                finalHolder.parent_cam_layout.setVisibility(View.GONE);
                holder.img_cam.setVisibility(View.GONE);
            }

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

            if (holder.data.getCam_image().equals("")) {
                holder.img_cam.setBackgroundResource(R.mipmap.camera_star);
                holder.img_cam.setId(childPosition);
            } else {
                holder.img_cam.setBackgroundResource(R.mipmap.camera_bsd);
                holder.img_cam.setId(childPosition);
            }

            if (!checkflag) {
                if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) {
                    holder.card_view.setBackgroundColor(getResources().getColor(io.github.memfis19.annca.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 MasterSurvey headerTitle = (MasterSurvey) getGroup(groupPosition);

            TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header);
            CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists);
            lblListHeader.setText(headerTitle.getSurveyName());

            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (expandableListView.isGroupExpanded(groupPosition)) {
                        expandableListView.collapseGroup(groupPosition);
                    } else {
                        expandableListView.expandGroup(groupPosition);
                    }
                }
            });

            if (!checkflag) {
                if (checkGroupArray.contains(groupPosition)) {
                    cardView.setBackgroundColor(getResources().getColor(io.github.memfis19.annca.R.color.red));
                } else {
                    cardView.setBackgroundColor(getResources().getColor(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;
            public final ImageView img_cam;
            public final RelativeLayout parent_cam_layout;
            CardView card_view;
            BASurveyGetterSetter data;

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

    }


    private static class AnswerSpinnerAdapter extends ArrayAdapter<BASurveyGetterSetter> {
        List<BASurveyGetterSetter> list;
        Context context;
        int resourceId;

        public AnswerSpinnerAdapter(Context context, int resourceId, ArrayList<BASurveyGetterSetter> 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);
            BASurveyGetterSetter cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_ans);
            txt_spinner.setText(list.get(position).getSurveyAnswer());

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

            BASurveyGetterSetter cm = list.get(position);

            TextView txt_spinner = (TextView) view.findViewById(R.id.tv_ans);
            txt_spinner.setText(cm.getSurveyAnswer());

            return view;
        }
    }

    boolean validateData(ArrayList<MasterSurvey> listDataHeader, HashMap<MasterSurvey, ArrayList<BASurveyGetterSetter>> listDataChild) {
        checkHeaderArray.clear();
        checkGroupArray.clear();
        loop:
        for (int j = 0; j < listDataHeader.size(); j++) {
            ArrayList<BASurveyGetterSetter> data = listDataChild.get(listDataHeader.get(j));
            for (int i = 0; i < Objects.requireNonNull(data).size(); i++) {
                if (data.get(i).getSurveyQuestionType().equalsIgnoreCase("Text") || data.get(i).getSurveyQuestionType().equalsIgnoreCase("Decimal") || data.get(i).getSurveyQuestionType().equalsIgnoreCase("Number")) {
                    if (data.get(i).getSurveyAnswer() == null || data.get(i).getSurveyAnswer().equalsIgnoreCase("")) {
                        error_msg = getString(R.string.pls_answer);
                        checkflag = false;
                    } else {
                        checkflag = true;
                    }
                } else {
                    if (data.get(i).getCorrect_answer_id().equalsIgnoreCase("0")) {
                        error_msg = getString(R.string.pls_answer_all_qns);
                        checkflag = false;
                    } else if (data.get(i).getImageAllow().equals("1") && data.get(i).getCam_image().equals("")) {
                        error_msg = getString(R.string.click_image);
                        checkflag = false;
                    } else {
                        checkflag = true;
                    }
                }
                if (!checkflag) {
                    if (!checkHeaderArray.contains(i)) {
                        checkHeaderArray.add(i);
                        checkGroupArray.add(j);
                    }
                    break loop;
                }
            }
        }
        adapter.notifyDataSetChanged();
        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()) {
                        convertBitmap(CommonString.getImagesFolder(context) + pathforcheck);
                        img_str = pathforcheck;
                        pathforcheck = "";
                        adapter.notifyDataSetChanged();
                    }
                }

        }
    }
}
