package cpm.com.gskmtorange.dailyentry;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
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.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

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

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.AddittionalGetterSetter;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.xmlGetterSetter.AdditionalQuestiongetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.AuditDataGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.T2PGetterSetter;

public class AuditActivity extends AppCompatActivity {
    private Context context;
    List<Integer> checkHeaderArray = new ArrayList<>();
    boolean checkflag = true;
    private SharedPreferences preferences;
    String categoryName, categoryId, Error_Message = "", pathforcheck = "", _path = "", str, img_str = "", img_str2 = "";
    String store_id, visit_date, username, intime, date, keyAccount_id, class_id, storeType_id, store_flag_str, country_id = "";
    GSKOrangeDB db;
    ArrayList<AuditDataGetterSetter> question_list = new ArrayList<>(), childListData;
    HashMap<AuditDataGetterSetter, ArrayList<AuditDataGetterSetter>> hashMapAnsListChildData;
    AnswerAdapter questionAdapter;
    RecyclerView recyclerView;
    Uri outputFileUri;
    String gallery_package = "";
    int child_position = -1;
    String error_msg = "";
    Toolbar toolbar;
    LinearLayout no_data_lay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audit);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        no_data_lay = (LinearLayout) findViewById(R.id.no_data_lay);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        date = preferences.getString(CommonString.KEY_DATE, null);
        username = preferences.getString(CommonString.KEY_USERNAME, null);
        intime = preferences.getString(CommonString.KEY_STORE_IN_TIME, "");
        keyAccount_id = preferences.getString(CommonString.KEY_KEYACCOUNT_ID, "");
        class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
        storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");
        store_flag_str = preferences.getString(CommonString.KEY_STORE_FLAG, null);
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
        toolbar.setTitle(getResources().getString(R.string.audit));
        str = CommonString.getImagesFolder(context);
        recyclerView = (RecyclerView) findViewById(R.id.list);

        db = new GSKOrangeDB(this);
        db.open();

        //Intent data
        categoryName = getIntent().getStringExtra("categoryName");
        categoryId = getIntent().getStringExtra("categoryId");

        //Header
        question_list = db.getAfterSaveAuditQuestionAnswerData(store_id, categoryId);
        if (question_list.size() == 0) {
            question_list = getAuditQnsRemoved();
        }

        hashMapAnsListChildData = new HashMap<>();
        childListData = new ArrayList<>();

        if (question_list.size() > 0) {
            String select = getString(R.string.title_activity_select_dropdown);
            // Adding child data
            for (int i = 0; i < question_list.size(); i++) {
                childListData = db.getAuditAnswerData(question_list.get(i).getQUESTION_ID(), categoryId, storeType_id, select);
                ArrayList<AuditDataGetterSetter> answerList = new ArrayList<>();
                for (int j = 0; j < childListData.size(); j++) {
                    answerList.add(childListData.get(j));
                }

                hashMapAnsListChildData.put(question_list.get(i), answerList); // Header, Child data
            }

            questionAdapter = new AnswerAdapter(question_list, hashMapAnsListChildData);
            recyclerView.setAdapter(questionAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        } else {
            no_data_lay.setVisibility(View.VISIBLE);
            fab.hide();//setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
        }

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                if (dy > 0  && fab.isShown())
                {
                    fab.hide();
                }

                if (dy < 0 && !fab.isShown())
                {
                    fab.show();
                }
            }

           /* @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState)
            {
                if (newState == RecyclerView.SCROLL_STATE_IDLE)
                {
                    fab.show();
                }

                super.onScrollStateChanged(recyclerView, newState);
            }*/
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (question_list.size() > 0) {
                    recyclerView.clearFocus();
                    if (validateData(question_list)) {
                        db.saveAuditQuestionAnswerData(question_list, store_id, categoryId);
                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    } else {
                        questionAdapter.notifyDataSetChanged();
                        Snackbar.make(recyclerView, error_msg, Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(recyclerView, getString(R.string.NodataAvailable), Snackbar.LENGTH_SHORT).show();
                }
            }
        });
    }

    ArrayList<AuditDataGetterSetter> getAuditQnsRemoved() {

        boolean t2p_flag = false;

        boolean flag_t2p_mapping;
        if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
            flag_t2p_mapping = db.isMappingT2PData(store_id, categoryId, CommonString.TABLE_MAPPING_T2P_ADHOC);
        } else {
            flag_t2p_mapping = db.isMappingT2PData(store_id, categoryId, CommonString.TABLE_MAPPING_T2P);
        }

        if (flag_t2p_mapping) {
            if (db.isFilledT2P(store_id, categoryId)) {
                ArrayList<T2PGetterSetter> t2PList = db.getT2pComplianceData(store_id, categoryId);

                for (int i = 0; i < t2PList.size(); i++) {
                    if (t2PList.get(i).getPresent() == 1) {
                        t2p_flag = true;
                        break;
                    }
                }
            }
        }

        if (!t2p_flag) {
            if (db.additionalVisibilitydata(store_id, categoryId)) {
                ArrayList<AddittionalGetterSetter> additionalList = db.getAdditionalMainStock(store_id, categoryId);
                for (int i = 0; i < additionalList.size(); i++) {
                    if (additionalList.get(i).getBtn_toogle().equals("1")) {
                        t2p_flag = true;
                        break;
                    }
                }
            }
        }

        ArrayList<AuditDataGetterSetter> question_list = db.getAuditCategoryWise(categoryId, storeType_id);
        Iterator<AuditDataGetterSetter> iterator = question_list.iterator();
        while (iterator.hasNext()) {
            AuditDataGetterSetter item = iterator.next(); // must be called before you can call iterator.remove()
            // Check condition
            if (!item.getKEYACCOUNT_ID().equals("0") && !item.getKEYACCOUNT_ID().equals(keyAccount_id)) {
                iterator.remove();
            } else if (!item.getCHECK_TYPE().equals("NA") && item.getCHECK_TYPE().equals("T2P")) {

                if (!t2p_flag) {
                    iterator.remove();
                }
            }
        }

        return question_list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        toolbar.setTitle(getResources().getString(R.string.audit));
    }

    @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 (question_list.size() > 0) {
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(AuditActivity.this);
                builder.setTitle("Parinaam");
                builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                        .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                finish();
                                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            }
                        }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                android.app.AlertDialog alert = builder.create();
                alert.show();
            } else {
                finish();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (question_list.size() > 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(AuditActivity.this);
            builder.setTitle("Parinaam");
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }


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

    }

    class AnswerAdapter extends RecyclerView.Adapter<AnswerAdapter.ViewHolder> {
        ArrayList<AuditDataGetterSetter> questionList;
        HashMap<AuditDataGetterSetter, ArrayList<AuditDataGetterSetter>> answerHashMap;

        public AnswerAdapter(ArrayList<AuditDataGetterSetter> questionList,
                             HashMap<AuditDataGetterSetter, ArrayList<AuditDataGetterSetter>> answerHashMap) {
            this.questionList = questionList;
            this.answerHashMap = answerHashMap;
        }

        public AnswerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.audit_question_list_item, parent, false);
            return new ViewHolder(view);
        }

        public void onBindViewHolder(final AnswerAdapter.ViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            holder.data = questionList.get(position);
            holder.txt_question.setText(holder.data.getQUESTION());
            holder.txt_question.setId(position);

           // Log.e("mandate_data",holder.data.getCAMERA_ALLOW()+","+holder.data.getCAMERA_MANDATORY() + "," + holder.data.getQUESTION_ID());

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

            if (holder.data.getANSWER_TYPE().equalsIgnoreCase("Dropdown")) {
                holder.sp_auditAnswer.setVisibility(View.VISIBLE);
                holder.sp_auditAnswer.setId(position);
                holder.edt_answer.setVisibility(View.GONE);
                holder.edt_answer.setId(position);
            }
            else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("TEXTBOX")) {
                int maxLength = Integer.parseInt(holder.data.getMaxlength());
                InputFilter[] fArray = new InputFilter[1];
                fArray[0] = new InputFilter.LengthFilter(maxLength);
                holder.edt_answer.setFilters(fArray);
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_TEXT);
                holder.edt_answer.setVisibility(View.VISIBLE);
                holder.edt_answer.setId(position);
                if (country_id.equals("4")) {
                    holder.edt_answer.setHint(R.string.pls_fill_stock_count);
                    holder.edt_answer.setId(position);
                }

                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(position);

            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("DECIMAL")) {
                int maxLength = Integer.parseInt(holder.data.getMaxlength());
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
                holder.edt_answer.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(maxLength, 2)});

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

                if (country_id.equals("4")) {
                    holder.edt_answer.setHint(R.string.pls_fill_stock_count);
                }

                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(position);

            } else if (holder.data.getANSWER_TYPE().equalsIgnoreCase("NUMBER")) {
                int maxLength = Integer.parseInt(holder.data.getMaxlength());
                InputFilter[] fArray = new InputFilter[1];
                fArray[0] = new InputFilter.LengthFilter(maxLength);
                holder.edt_answer.setFilters(fArray);
                holder.edt_answer.setInputType(InputType.TYPE_CLASS_NUMBER);

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

                if (country_id.equals("4")) {
                    holder.edt_answer.setHint(R.string.pls_fill_stock_count);
                }

                holder.sp_auditAnswer.setVisibility(View.GONE);
                holder.sp_auditAnswer.setId(position);
            }

            if (holder.data.getCAMERA_ALLOW().equals("1")) {
                holder.parent_cam_layout.setVisibility(View.VISIBLE);
                holder.parent_cam_layout.setId(position);
            } else {
                holder.parent_cam_layout.setVisibility(View.GONE);
                holder.parent_cam_layout.setId(position);
            }
            //text
            if (holder.data.getREMARK_ALLOW().equals("1")) {
                holder.edt_text.setVisibility(View.VISIBLE);
                holder.edt_text.setId(position);

                holder.txt_leval.setVisibility(View.VISIBLE);
                holder.txt_leval.setText(holder.data.getREMARK_LEVEL());
                holder.txt_leval.setId(position);
            } else {
                holder.edt_text.setVisibility(View.GONE);
                holder.edt_text.setId(position);
                holder.txt_leval.setVisibility(View.GONE);
                holder.txt_leval.setId(position);
            }

            holder.sp_auditAnswer.setAdapter(new AnswerSpinnerAdapter(AuditActivity.this, R.layout.custom_spinner_item, ans_list));

            final ArrayList<AuditDataGetterSetter> finalAns_list = ans_list;
            holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    AuditDataGetterSetter ans = finalAns_list.get(position);
                    holder.data.setANSWER_ID(ans.getANSWER_ID());
                    holder.data.setANSWER(ans.getANSWER());
                    holder.data.setCAMERA_ALLOW(ans.getCAMERA_ALLOW());
                    holder.data.setREMARK_ALLOW(ans.getREMARK_ALLOW());
                    holder.data.setREMARK_LEVEL(ans.getREMARK_LEVEL());
                    holder.data.setCAMERA_MANDATORY(ans.getCAMERA_MANDATORY());

                    Log.e("mandate_data",holder.data.getCAMERA_ALLOW() + ","+ holder.data.getCAMERA_MANDATORY());

                    //text
                    if (holder.data.getREMARK_ALLOW().equals("1")) {
                        holder.edt_text.setVisibility(View.VISIBLE);
                        holder.txt_leval.setVisibility(View.VISIBLE);
                        holder.txt_leval.setText(holder.data.getREMARK_LEVEL());
                    } else {
                        holder.edt_text.setVisibility(View.GONE);
                        holder.txt_leval.setVisibility(View.GONE);
                        holder.data.setTXT_REMARK("");
                    }

                    if (holder.data.getCAMERA_ALLOW().equals("1")) {
                        holder.parent_cam_layout.setVisibility(View.VISIBLE);
                        if (ans.getNO_OF_CAMERA().equals("2")) {
                            holder.img_cam2.setVisibility(View.VISIBLE);
                        } else {
                            holder.img_cam2.setVisibility(View.GONE);
                        }
                    } else {
                        holder.parent_cam_layout.setVisibility(View.GONE);
                        if (holder.data.getCAM_IMAGE() != null && holder.data.getCAM_IMAGE().equals("")) {
                            if (new File(str + holder.data.getCAM_IMAGE()).exists()) {
                                new File(str + holder.data.getCAM_IMAGE()).delete();
                            }
                        }
                        if (holder.data.getCAM_IMAGE2() != null && holder.data.getCAM_IMAGE2().equals("")) {
                            if (new File(str + holder.data.getCAM_IMAGE2()).exists()) {
                                new File(str + holder.data.getCAM_IMAGE2()).delete();
                            }
                        }
                        holder.data.setCAM_IMAGE("");
                        holder.data.setCAM_IMAGE2("");
                        holder.img_cam.setBackgroundResource(R.mipmap.camera_orange);
                        holder.img_cam2.setBackgroundResource(R.mipmap.camera_orange);
                    }
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            holder.img_cam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     pathforcheck = store_id + "AuditAnsPic" + categoryId + date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context)+ pathforcheck;
                    intime = CommonFunctions.getCurrentTimeWithLanguage(context);
                    child_position = position;
                    startCameraActivity(0);
                }
            });

            holder.img_cam2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pathforcheck = store_id + "AuditAnsPic2" + categoryId + date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";

                    _path = CommonString.getImagesFolder(context)+ pathforcheck;
                    intime = CommonFunctions.getCurrentTimeWithLanguage(context);
                    child_position = position;
                    startCameraActivity(1);
                }
            });

            holder.edt_answer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        if (holder.data.getANSWER_TYPE().equalsIgnoreCase("NUMBER")) {
                            holder.data.setANSWER_ID("0");
                            holder.data.setANSWER(((EditText) v).getText().toString().replaceFirst("^0+.(?!$)", ""));
                        } else {
                            holder.data.setANSWER_ID("0");
                            holder.data.setANSWER(((EditText) v).getText().toString().replaceAll("[&^<>{}'$]", ""));
                        }

                    }
                }
            });

            //set remark
            holder.edt_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        holder.data.setTXT_REMARK(((EditText) v).getText().toString().replaceAll("[&^<>{}'$]", ""));
                    }
                }
            });

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

            if (holder.data.getANSWER_TYPE().equalsIgnoreCase("TEXTBOX")
                    || holder.data.getANSWER_TYPE().equalsIgnoreCase("DECIMAL")
                    || holder.data.getANSWER_TYPE().equalsIgnoreCase("NUMBER")) {
                holder.edt_answer.setText(holder.data.getANSWER());
                holder.edt_answer.setId(position);
            }

            //set text
            if (holder.data.getREMARK_ALLOW().equalsIgnoreCase("1")) {
                holder.edt_text.setText(holder.data.getTXT_REMARK());
                holder.edt_text.setId(position);
            }

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

            if (!img_str2.equals("")) {
                if (child_position == position) {
                    holder.data.setCAM_IMAGE2(img_str2);
                    img_str2 = "";
                    child_position = -1;
                }
            }

            if (holder.data.getCAM_IMAGE().equals("")) {
                holder.img_cam.setBackgroundResource(R.mipmap.camera_orange);
                holder.img_cam.setId(position);

            } else {
                holder.img_cam.setBackgroundResource(R.mipmap.camera_green);
                holder.img_cam.setId(position);
            }

            if (holder.data.getCAM_IMAGE2().equals("")) {
                holder.img_cam2.setBackgroundResource(R.mipmap.camera_orange);
                holder.img_cam2.setId(position);
            } else {
                holder.img_cam2.setBackgroundResource(R.mipmap.camera_green);
                holder.img_cam2.setId(position);
            }


            if (!checkflag) {
                if (checkHeaderArray.contains(position)) {
                    holder.card_view.setBackgroundColor(getResources().getColor(R.color.red));
                    holder.card_view.setId(position);
                } else {
                    holder.card_view.setBackgroundColor(getResources().getColor(R.color.white));
                    holder.card_view.setId(position);
                }
            }
        }

        @Override
        public int getItemCount() {
            return questionList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView txt_question, txt_leval;
            public final Spinner sp_auditAnswer;
            public final EditText edt_answer, edt_text;
            public final ImageView img_cam, img_cam2;
            public final RelativeLayout parent_cam_layout;
            CardView card_view;
            AuditDataGetterSetter data;

            public ViewHolder(View view) {
                super(view);
                mView = view;

                txt_leval = (TextView) view.findViewById(R.id.txt_leval);
                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_text = (EditText) view.findViewById(R.id.edt_text);
                edt_answer = (EditText) view.findViewById(R.id.edt_answer);
                img_cam = (ImageView) view.findViewById(R.id.img_cam);
                img_cam2 = (ImageView) view.findViewById(R.id.img_cam2);
                parent_cam_layout = (RelativeLayout) view.findViewById(R.id.parent_cam_layout);
            }
        }
    }


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

        @Override
        public View getView(int position, View convertView, 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, 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<AuditDataGetterSetter> data) {
        //boolean flag = true;
        checkHeaderArray.clear();

        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("TEXTBOX") && data.get(i).getANSWER().equalsIgnoreCase("")
                    || data.get(i).getANSWER_TYPE().equalsIgnoreCase("DECIMAL") && data.get(i).getANSWER().equalsIgnoreCase("")
                    || data.get(i).getANSWER_TYPE().equalsIgnoreCase("NUMBER") && data.get(i).getANSWER().equalsIgnoreCase("")) {
                error_msg = getString(R.string.pls_answer_all_qns);
                checkflag = false;
            } else if (data.get(i).getANSWER_TYPE().equalsIgnoreCase("DROPDOWN") && 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).getCAMERA_MANDATORY().equals("1")  && data.get(i).getCAM_IMAGE().equals("")) {
                error_msg = getString(R.string.click_image);
                checkflag = false;
            } else if (data.get(i).getCAMERA_ALLOW().equals("1")  && data.get(i).getCAMERA_MANDATORY().equals("1")
                    && data.get(i).getNO_OF_CAMERA().equals("2") && data.get(i).getCAM_IMAGE2().equals("")) {
                error_msg = getString(R.string.click_image);
                checkflag = false;
                //text
            } else if (data.get(i).getREMARK_ALLOW().equals("1") && data.get(i).getTXT_REMARK().equals("")) {
                error_msg = getString(R.string.pleaseenterRemarks);
                checkflag = false;
            } else {
                checkflag = true;
            }

            if (checkflag == false) {
                if (!checkHeaderArray.contains(i)) {
                    checkHeaderArray.add(i);
                }
                break;
            }
        }
        return checkflag;
    }

    protected void startCameraActivity(int code) {
        try {

            Log.i("MakeMachine", "startCameraActivity()");
            File file = new File(_path);
            outputFileUri = FileProvider.getUriForFile(context, "cpm.com.gskmtorange.fileprovider", file);

            String defaultCameraPackage = "";
            final PackageManager packageManager = getPackageManager();
            List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
            for (int n = 0; n < list.size(); n++) {
                if ((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                    Log.e("TAG", "Installed Applications  : " + list.get(n).loadLabel(packageManager).toString());
                    Log.e("TAG", "package name  : " + list.get(n).packageName);

                    //temp value in case camera is gallery app above jellybean
                    String packag = list.get(n).loadLabel(packageManager).toString();
                    if (packag.equalsIgnoreCase("Gallery") || packag.equalsIgnoreCase("Galeri") || packag.equalsIgnoreCase("الاستوديو")) {
                        gallery_package = list.get(n).packageName;
                    }

                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {
                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    } else {

                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {

                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    }
                }
            }

            //com.android.gallery3d

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(defaultCameraPackage);
            startActivityForResult(intent, code);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(gallery_package);
            startActivityForResult(intent, code);

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

    @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()) {
                        if (requestCode == 0) {
                            img_str = pathforcheck;
                        } else {
                            img_str2 = pathforcheck;
                        }

                        pathforcheck = "";
                        questionAdapter.notifyDataSetChanged();
                    }
                }

        }
    }
}
