package com.cpm.lorealbaautomation.dailyactivity;

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

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.google.android.material.bottomsheet.BottomSheetDialog;
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.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gettersetter.SaleableGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

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

public class DamagedActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    ArrayAdapter<CharSequence> axe_name_adapter, sub_axe_name_adapter, brand_name_adapter, product_name_adapter;
    Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin;
    ArrayList<ProductMaster> brandList = new ArrayList<>();
    ArrayList<ProductMaster> subAxeList = new ArrayList<>();
    ArrayList<ProductMaster> axeList = new ArrayList<>();

    ExpandableListView lvExp_stock_check;
    FloatingActionButton fab_save, return_fab;
    Lorealba_Database db;
    Context context;
    AlertDialog alert;
    private SharedPreferences preferences;
    String counter_id, visit_date, username, _pathforcheck, _path;
    ArrayList<ProductMaster> listDataHeader = new ArrayList<>();
    ArrayList<ProductMaster> childStockList = new ArrayList<>();
    HashMap<ProductMaster, List<ProductMaster>> listDataChild;
    boolean checkflag = true;
    ArrayList<Integer> checkHeaderArray = new ArrayList<>();
    ExpandableListAdapter listAdapter;
    String brandName = "";
    String axeName = "";
    String subAxeName = "";

    int groupPositionGlobal = -1;
    ProductMaster globalHeaderObject = new ProductMaster();
    EditText et_search;

    //filter bottom sheet
    ArrayList<ProductMaster> subBrandList = new ArrayList<>();
    ArrayList<ProductMaster> referenceList = new ArrayList<>();
    ArrayList<ProductMaster> signatureList = new ArrayList<>();
    ImageView img_filter, img_unfilled;
    View sheetView;
    ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference;
    final int FILTER_FOR_SIGNATURE = 4;
    final int FILTER_FOR_SUB_BRAND = 5;
    final int FILTER_FOR_REFERENCE = 6;
    final int FILTER_FOR_BRAND = 1;
    final int CLEAR_FILTER = 0;

    int childPositionGlobal = -1;
    ProductMaster globalChildObject = new ProductMaster();

    ImageView img_scan, img_clear_subaxe;
    RecyclerView recSubAxe;
    SubAxeValueAdapter subAxeValueAdapter;
    ArrayList<ProductMaster> listSubAxe;
    boolean flagScan = true;
    private String counterGroupId, damaged_category_str = "", selectedSubAxe = "";
    TextView txt_total_qty, txt_total_value;
    LinearLayout rl_total_qty;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_damaged);
        context = this;
        ((DamagedActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();
        validateUIData();

        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_id);

        new LoadAsync().execute();
        lvExp_stock_check.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lvExp_stock_check.invalidate();

                int lastItem = firstVisibleItem + visibleItemCount;
                if (firstVisibleItem == 0) {
                    fab_save.show();//.setVisibility(View.VISIBLE);
                } else if (lastItem == totalItemCount) {
                    fab_save.hide();//setVisibility(View.INVISIBLE);
                } else {
                    fab_save.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();
                }

                lvExp_stock_check.invalidateViews();
            }
        });

    }

    private void validateUIData() {
        preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        damaged_category_str = getIntent().getStringExtra(CommonString.TAG_OBJECT);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        sku_spin = (Spinner) findViewById(R.id.sku_spin);
        brand_spin = (Spinner) findViewById(R.id.stock_brand_spin);
        sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin);
        axe_spin = (Spinner) findViewById(R.id.axe_spin);
        lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check);
        fab_save = (FloatingActionButton) findViewById(R.id.save_fab);

        et_search = (EditText) findViewById(R.id.et_search);
        img_scan = (ImageView) findViewById(R.id.img_scan);
        img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe);

        recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        ////for total QTY and Return value..........
        rl_total_qty = (LinearLayout) findViewById(R.id.rl_total_qty);
        txt_total_qty = (TextView) findViewById(R.id.txt_total_qty);
        txt_total_value = (TextView) findViewById(R.id.txt_total_value);

        img_scan.setOnClickListener(this);
        fab_save.setOnClickListener(this);
        img_clear_subaxe.setOnClickListener(this);
        if (damaged_category_str != null && damaged_category_str.equals("1")) {
            setTitle("Damaged Stock - " + visit_date);
        } else {
            setTitle("Return To distributor - " + visit_date);
            fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.submit));
        }

        db.open();
        img_clear_subaxe.setVisibility(View.VISIBLE);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = s.toString();
                if (text.equals("")) {
                    lvExp_stock_check.setAdapter(listAdapter);
                    listAdapter.notifyDataSetChanged();
                } else {
                    lvExp_stock_check.invalidate();
                    setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
            }
        });


        img_filter = (ImageView) findViewById(R.id.img_filter);
        img_unfilled = (ImageView) findViewById(R.id.img_unfilled);
        img_unfilled.setVisibility(View.INVISIBLE);

        img_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sheetView = showFilterBottomSheet();
            }
        });
    }

    public void setSearchFilter(List<ProductMaster> originalList, String text, HashMap<ProductMaster, List<ProductMaster>> listDataChild) {
        HashMap<ProductMaster, List<ProductMaster>> filterChildHashMap = new HashMap<>();
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (int i = 0; i < originalList.size(); i++) {
            ProductMaster parent = originalList.get(i);
            List<ProductMaster> listChild = listDataChild.get(parent);
            List<ProductMaster> listFilterChild = new ArrayList<>();
            for (int j = 0; j < listChild.size(); j++) {
                if (listChild.get(j).getProductName().toLowerCase().contains(text.toLowerCase()) || (listChild.get(j).getEanCode() != null && listChild.get(j).getEanCode().contains(text))) {
                    listFilterChild.add(listChild.get(j));
                } else {
                    continue;
                }
            }

            if (listFilterChild.size() > 0) {
                filterList.add(parent);
                filterChildHashMap.put(parent, listFilterChild);

            }

        }

        ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap);
        lvExp_stock_check.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
        for (int i = 0; i < listAdapter.getGroupCount(); i++) {
            lvExp_stock_check.expandGroup(i);
        }

    }

    private void prepareListData() {
        db.open();
        //for filter bottom sheet
        JourneyPlan jcp = db.getJCP();
        if (jcp != null) {
            db.open();
            listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true);
            db.open();
            brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false);
            db.open();
            subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false);
            db.open();
            referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false);
            db.open();
            signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false);
        } else {
            db.open();
            brandList = db.getsub_brand_name("1", "BrandName", false);
            db.open();
            subBrandList = db.getsub_brand_name("1", "SubBrandName", false);
            db.open();
            referenceList = db.getsub_brand_name("1", "ReferenceName", false);
            db.open();
            signatureList = db.getsub_brand_name("1", "SignatureName", false);
            db.open();
            listSubAxe = db.getSubAxe("1", true);
        }

        listDataHeader = new ArrayList<>();
        listDataChild = new HashMap<>();
        //inserted data
        if (listDataHeader.size() == 0) {
            jcp = db.getJCP();
            if (jcp != null) {
                if (damaged_category_str != null) {
                    db.open();
                    listDataHeader = db.getDamageBrandSubBrandReference(jcp.getCounterGroupId().toString(), counter_id, visit_date, damaged_category_str);
                }
            } else {
                db.open();
                listDataHeader = db.getStockSignatureBrandSubBrandReference("1", false, false, null);
            }
        }

        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                if (damaged_category_str != null) {
                    db.open();
                    childStockList = db.getDefaultDamageChildData(counter_id, visit_date, listDataHeader.get(i).getSubBrandName(),
                            listDataHeader.get(i).getReferenceName(), listDataHeader.get(i).getBrandName(),
                            CommonString.KEY_SaleableDamage, damaged_category_str, jcp.getCounterGroupId().toString());
                }

                listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data
            }
        }
    }


    private boolean isValid() {
        boolean flag = true;
        for (int i = 0; i < listDataHeader.size(); i++) {
            List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getStock() > 0 && list.get(j).getImagePath().equals("")) {
                    flag = false;
                    break;
                }
            }

            if (!flag) {
                break;
            }
        }

        return flag;
    }


    private void show_dialog_for_final_submit(final Context context, final boolean returntodistr) {
        final MultiPurposeDialog final_save_dialog = new MultiPurposeDialog(context);
        final_save_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        final_save_dialog.setContentView(R.layout.custom_dialog_final_save);
        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(final_save_dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        final_save_dialog.getWindow().setAttributes(lp);
        final_save_dialog.setCancelable(false);

        final EditText txt_hint_yes = (EditText) final_save_dialog.findViewById(R.id.txt_hint_yes);
        Button btn_cancel = (Button) final_save_dialog.findViewById(R.id.btn_cancel);
        Button btn_okay = (Button) final_save_dialog.findViewById(R.id.btn_okay);

        TextView final_text = (TextView) final_save_dialog.findViewById(R.id.final_text);
        if (returntodistr) {
            final_text.setText(getString(R.string.want_to_final_savedamage));
        } else {
            final_text.setText(getString(R.string.want_to_final_damage_save));
        }

        btn_okay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txt_hint_yes.getText().toString().equals("")) {
                    AlertandMessages.showToastMsg(context, "Please Enter Text");
                } else if (!txt_hint_yes.getText().toString().trim().equalsIgnoreCase("yes")) {
                    AlertandMessages.showToastMsg(context, "Please Enter 'Yes' Text");
                } else {
                    ////final submit
                    final_save_dialog.dismiss();
                    if (returntodistr) {
                        dialog = new Dialog(context);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        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();
                        /*if (CommonFunctions.checkNetIsAvailable(context)) {
                            UploadDamageReturnToDistributor();
                        } else {*/
                        final SaleableGetterSetter stock = new SaleableGetterSetter();
                        ArrayList<ProductMaster> data = new ArrayList<>();
                        for (int i = 0; i < listDataHeader.size(); i++) {
                            List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
                            for (int j = 0; j < list.size(); j++) {
                                if (list.get(j).getStock() > 0) {
                                    data.add(list.get(j));
                                }
                            }
                        }

                        if (data.size() > 0) {
                            stock.setProductList(data);
                            String uuid = CommonFunctions.getUUID(context);
                            stock.setTransactionId(uuid);
                        }

                        if (stock != null) {
                            db.open();
                            db.updateTStockSaleableDamageReturnData();
                            db.open();
                            db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.RETURNTO_DB, stock, "Regular_Stock");
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            CommonFunctions.call_upload(context);
                            DamagedActivity.this.finish();
                        }
                        // }
                    } else {
                        dialog = new Dialog(context);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        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();
                        db.open();
                        db.insertDamagedCapturedData(visit_date, counter_id, listDataChild, listDataHeader);
                        uploadData();
                    }
                }
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final_save_dialog.dismiss();
            }
        });

        final_save_dialog.show();
    }

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


    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.save_fab) {
            lvExp_stock_check.clearFocus();
            lvExp_stock_check.invalidateViews();

            if (damaged_category_str != null && damaged_category_str.equals("1")) {
                if (isValid()) {
                    dialogFinalSubmit(false);
                } else {
                    AlertandMessages.showToastMsg(context, getString(R.string.pls_click_image_damage));
                }
            } else if (damaged_category_str != null && damaged_category_str.equals("0")) {
                if (calculate_total_qty() > 0) {
                    dialogFinalSubmit(true);
                } else {
                    AlertandMessages.showToastMsg(context, "Please Return To Distributor atleast one product");
                }
            }

        } else if (view.getId() == R.id.card_signature) {
            RecyclerView recSignature = sheetView.findViewById(R.id.rec_brand);
            recSignature.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature));
            recSignature.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            setFilterSelected(sheetView, CommonString.Signature);

        } else if (view.getId() == R.id.card_brand) {

            RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand);
            recBrand.setAdapter(new ValueAdapter(context, brandList, CommonString.Brand));
            recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            setFilterSelected(sheetView, CommonString.Brand);
        } else if (view.getId() == R.id.card_sub_brand) {

            RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand);
            recSubBrand.setAdapter(new ValueAdapter(context, subBrandList, CommonString.SubBrand));
            recSubBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            recSubBrand.getAdapter().notifyDataSetChanged();
            setFilterSelected(sheetView, CommonString.SubBrand);
        } else if (view.getId() == R.id.card_reference) {

            RecyclerView recReference = sheetView.findViewById(R.id.rec_brand);
            recReference.setAdapter(new ValueAdapter(context, referenceList, CommonString.Reference));
            recReference.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
            setFilterSelected(sheetView, CommonString.Reference);
        } else if (view.getId() == R.id.img_scan) {
            if (flagScan) {
                openScanner();
            } else {
                img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.barcode_icon));
                flagScan = true;
                et_search.setText("");
            }

        } else if (view.getId() == R.id.img_clear_subaxe) {
            et_search.setText("");
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
            lvExp_stock_check.setAdapter(listAdapter);
            listAdapter.notifyDataSetChanged();
            selectedSubAxe = "";
            subAxeValueAdapter.notifyDataSetChanged();

            //clear filters also
            selectedSignature = null;
            selectedBrand = null;
            selectedSubBrand = null;
            selectedReference = null;
            db.open();
            brandList = db.getsub_brand_name(counterGroupId, "BrandName", false, selectedSubAxe);
            db.open();
            subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe);
            db.open();
            referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe);
            db.open();
            signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe);

        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
        if (adapterView.getId() == R.id.stock_brand_spin) {
            if (position != 0) {
                brandName = adapterView.getSelectedItem().toString();
                setFilter(FILTER_FOR_BRAND);
                db.open();
                //for filter bottom sheet
                JourneyPlan jcp = db.getJCP();
                if (jcp != null) {
                    db.open();
                    axeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "AxeName", brandName, null);
                    db.open();
                    subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", brandName, null);
                } else {
                    db.open();
                    axeList = db.getAxeNSubAxe("1", "AxeName", brandName, null);
                    db.open();
                    subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null);
                }
                setAxeSpinnerData(axeList);
                setSubAxeSpinnerData(subAxeList);

            } else {
                brandName = "";
                setFilter(CLEAR_FILTER);
                db.open();
                //for filter bottom sheet
                JourneyPlan jcp = db.getJCP();
                if (jcp != null) {
                    db.open();
                    axeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "AxeName", null, null);
                    db.open();
                    subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", null, null);
                } else {
                    db.open();
                    axeList = db.getAxeNSubAxe("1", "AxeName", null, null);
                    db.open();
                    subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null);
                }
                setAxeSpinnerData(axeList);
                setSubAxeSpinnerData(subAxeList);
            }

        } else if (adapterView.getId() == R.id.axe_spin) {
            if (position != 0) {
                axeName = adapterView.getSelectedItem().toString();
                setFilter(FILTER_FOR_AXE);
                db.open();
                //for filter bottom sheet
                JourneyPlan jcp = db.getJCP();
                if (jcp != null) {
                    db.open();
                    subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", "", axeName);
                } else {
                    db.open();
                    subAxeList = db.getAxeNSubAxe("1", "SubAxeName", "", axeName);
                }

                setSubAxeSpinnerData(subAxeList);
            } else {
                axeName = "";
                if (brand_spin.getSelectedItemPosition() == 0) {
                    db.open();
                    //for filter bottom sheet
                    JourneyPlan jcp = db.getJCP();
                    if (jcp != null) {
                        subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", null, null);
                    } else {
                        subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null);
                    }

                    setSubAxeSpinnerData(subAxeList);
                    setFilter(CLEAR_FILTER);
                } else {
                    db.open();
                    //for filter bottom sheet
                    JourneyPlan jcp = db.getJCP();
                    if (jcp != null) {
                        subAxeList = db.getAxeNSubAxe(jcp.getCounterGroupId().toString(), "SubAxeName", brandName, null);
                    } else {
                        subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null);
                    }

                    setSubAxeSpinnerData(subAxeList);
                    setFilter(FILTER_FOR_BRAND);
                }
            }

        } else if (adapterView.getId() == R.id.sub_axe_spin) {
            if (position != 0) {
                subAxeName = adapterView.getSelectedItem().toString();
                setFilter(FILTER_FOR_SUBAXE);
            } else {
                subAxeName = "";
                if (axe_spin.getSelectedItemPosition() == 0) {
                    if (brand_spin.getSelectedItemPosition() == 0) {
                        setFilter(CLEAR_FILTER);
                    } else {
                        setFilter(FILTER_FOR_BRAND);
                    }
                } else {
                    setFilter(FILTER_FOR_AXE);
                }
            }

        }

    }

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

    }

    public ArrayList<ProductMaster> filterListForBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getBrandName().equalsIgnoreCase(text)) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }


    public class ExpandableListAdapter extends BaseExpandableListAdapter {
        private Context _context;
        private List<ProductMaster> _listDataHeader;
        private HashMap<ProductMaster, List<ProductMaster>> _listDataChild;

        public ExpandableListAdapter(Context context, List<ProductMaster> listDataHeader, HashMap<ProductMaster, List<ProductMaster>> listChildData) {
            this._context = context;
            this._listDataHeader = listDataHeader;
            this._listDataChild = listChildData;
        }

        public HashMap<ProductMaster, List<ProductMaster>> get_listDataChild() {
            return _listDataChild;
        }

        public List<ProductMaster> get_listDataHeader() {
            return _listDataHeader;
        }

        @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({"UseCompatLoadingForDrawables", "SetTextI18n"})
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

            final ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition);
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_damage_layout, null);
                holder = new ViewHolder();
                holder.cardView = convertView.findViewById(R.id.card_view);
                holder.ed_Stock = convertView.findViewById(R.id.ed_Stock);
                holder.mrp = convertView.findViewById(R.id.mrp);
                holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus);
                holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus);
                holder.tv_stock_saleable = convertView.findViewById(R.id.tv_stock);
                holder.tv_damage = convertView.findViewById(R.id.tv_damage);
                holder.imgCam = convertView.findViewById(R.id.img_cam);
                convertView.setTag(holder);


            } else {

                holder = (ViewHolder) convertView.getTag();
            }


            holder.imgCam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    groupPositionGlobal = groupPosition;
                    childPositionGlobal = groupPosition;
                    globalChildObject = childText;
                    _pathforcheck = counter_id + "_Damaged_stock_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(DamagedActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            });

            TextView txtListChild = convertView.findViewById(R.id.lblListItem);
            txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")");

            holder.stock_img_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                    int stock = childText.getStock();
                    int receivedStock = childText.getStock_receive();
                    int saleable_stock = childText.getSaleable_stock();

                    if (damaged_category_str != null && damaged_category_str.equals("0")) {
                        ++stock;
                        if (stock > receivedStock) {
                            stock--;
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                            AlertandMessages.showToastMsg(context, "Damage cannot be greater than Received Stock");
                        } else {
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                        }
                        txt_total_qty.setText("Return Total QTY : " + calculate_total_qty());
                        txt_total_value.setText("Return Total Values : " + calculate_total_sale_value());
                    } else {
                        ++stock;
                        if (stock <= saleable_stock) {
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                        } else {
                            stock--;
                            AlertandMessages.showToastMsg(context, "Damage cannot be greater than Stock.");
                        }
                    }
                }
            });

            holder.stock_img_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                    int stock = childText.getStock();
                    //  int receivedStock = childText.getStock_receive();
                    int damaged_stock = childText.getSaleable_stock();
                    if (damaged_category_str != null && damaged_category_str.equals("0")) {
                        --stock;
                        if (stock >= 0) {
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                        } else {
                            AlertandMessages.showToastMsg(context, "Stock cannot be less than Zero");
                        }

                        txt_total_qty.setText("Return Total QTY : " + calculate_total_qty());
                        txt_total_value.setText("Return Total Values : " + calculate_total_sale_value());

                    } else {
                        --stock;
                        if (stock >= 0) {
                            isDataAdded = true;
                            childText.setStock(stock);
                            childText.setSelected(true);
                        } else {
                            AlertandMessages.showToastMsg(context, "Stock cannot be less than Zero");
                        }
                    }
                }
            });


            if (childText.getImagePath().isEmpty()) {
                holder.imgCam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs));
                holder.imgCam.setId(childPosition);
            } else {
                holder.imgCam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                holder.imgCam.setId(childPosition);
            }

            holder.mrp.setText(" MRP = " + childText.getMrp());
            holder.mrp.setId(childPosition);

            ///availeble Damage Stock
            if (damaged_category_str != null && damaged_category_str.equals("0")) {
                holder.ed_Stock.setText("Damaged Stock : " + childText.getStock());
                holder.ed_Stock.setId(childPosition);

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

                holder.tv_damage.setText("Return QTY : " + childText.getBlockproductId());
                holder.tv_damage.setId(childPosition);

                holder.tv_stock_saleable.setText("Saleable Damage : " + childText.getSaleable_stock());
                holder.tv_stock_saleable.setId(childPosition);

            } else if (damaged_category_str != null && damaged_category_str.equals("1")) {
                holder.ed_Stock.setText("" + childText.getStock());
                holder.ed_Stock.setId(childPosition);

                holder.tv_stock_saleable.setText("Stock - " + childText.getSaleable_stock());
                holder.tv_stock_saleable.setId(childPosition);

                holder.tv_damage.setText("Dmg - " + childText.getStock_receive());
                holder.tv_damage.setId(childPosition);

                holder.imgCam.setVisibility(View.VISIBLE);
                holder.imgCam.setId(childPosition);
            }


            if (damaged_category_str != null && damaged_category_str.equals("1") && childText.getBlockproductId() != 0) {
                holder.stock_img_plus.setEnabled(false);
                holder.stock_img_plus.setId(childPosition);

                holder.stock_img_minus.setEnabled(false);
                holder.stock_img_minus.setId(childPosition);

                holder.imgCam.setImageResource(R.mipmap.exclam);
                holder.imgCam.setEnabled(false);
                holder.imgCam.setId(childPosition);

            } else {
                holder.stock_img_plus.setEnabled(true);
                holder.stock_img_plus.setId(childPosition);

                holder.stock_img_minus.setEnabled(true);
                holder.stock_img_minus.setId(childPosition);

                holder.imgCam.setEnabled(true);
                holder.imgCam.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) {
            final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition);
            if (convertView == null) {

                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null);
            }
            TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
            ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam);

            stock_cam.setVisibility(View.GONE);
            stock_cam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    groupPositionGlobal = groupPosition;
                    globalHeaderObject = headerTitle;
                    _pathforcheck = counter_id + "_Damage_header_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(DamagedActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            });

            if (headerTitle.getImagePath().isEmpty()) {
                stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera));
            } else {
                stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick));
            }

            lblListHeader.setText(headerTitle.getSubBrandName() + " - " + headerTitle.getReferenceName() + " - " + headerTitle.getBrandName());
            if (!checkflag) {
                if (checkHeaderArray.contains(groupPosition)) {
                    lblListHeader.setBackgroundColor(getResources().getColor(R.color.red));
                } else {
                    lblListHeader.setBackgroundColor(getResources().getColor(R.color.bright_red));
                }

            } else {
                lblListHeader.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 {
        TextView ed_Stock, mrp, tv_stock_saleable, tv_damage;
        Button stock_img_plus, stock_img_minus;
        ImageView imgCam;
        CardView cardView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void setAxeSpinnerData(ArrayList<ProductMaster> axeList) {
        axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        axe_name_adapter.add("- Axe Name -");

        for (int i = 0; i < axeList.size(); i++) {
            axe_name_adapter.add(axeList.get(i).getBrandName());
        }

        axe_spin.setAdapter(axe_name_adapter);
        axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

    }

    private void setSubAxeSpinnerData(ArrayList<ProductMaster> subAxeList) {
        sub_axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        sub_axe_name_adapter.add("- Sub Axe Name -");


        for (int i = 0; i < subAxeList.size(); i++) {
            sub_axe_name_adapter.add(subAxeList.get(i).getBrandName());
        }

        sub_axe_spin.setAdapter(sub_axe_name_adapter);
        sub_axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

    }


    final int FILTER_FOR_AXE = 2;
    final int FILTER_FOR_SUBAXE = 3;

    boolean isDataAdded = false;

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        isChanged();
    }

    void isChanged() {
        if (isDataAdded) {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(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 {
            super.onBackPressed();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("MakeMachine", "resultCode: " + resultCode);

        if (requestCode == 131) {
            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);
                            isDataAdded = true;
                            globalChildObject.setImagePath(_pathforcheck);
                            groupPositionGlobal = -1;
                            childPositionGlobal = -1;
                            _pathforcheck = "";
                            listAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
            }
        } else {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            switch (resultCode) {
                case 0:
                    break;

                case -1:
                    db.open();
                    ArrayList<ProductMaster> productList = db.getsku_fromproductusing_eancode(result.getContents(), false, visit_date, counter_id, null);

                    if (productList.isEmpty()) {
                        db.open();
                        productList = db.getsku_fromproductusing_eancode(removeFirstChar(result.getContents()), false, visit_date, counter_id, null);
                    }

                    if (!productList.isEmpty()) {
                        flagScan = false;
                        img_scan.setImageDrawable(getResources().getDrawable(R.mipmap.ok));
                        clearFilters();
                        setScanFilter(productList);

                    } else {
                        AlertandMessages.showToastMsg(context, "Unable To Scan Correct Data. Please Try Again.");
                    }
                    break;
            }
        }

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

    //filter bottom sheet
    View showFilterBottomSheet() {
        String uniqueId = UUID.randomUUID().toString();
        final CardView cardSignature, cardBrand, cardSubBrand, cardReference;
        final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this);
        @SuppressLint("InflateParams") final View sheetView = getLayoutInflater().inflate(R.layout.filter_bottom_sheet, null);
        mBottomSheetDialog.setContentView(sheetView);
        View bottomSheet = mBottomSheetDialog.getWindow().findViewById(com.google.android.material.R.id.design_bottom_sheet);
        if (bottomSheet != null) {
            bottomSheet.setBackgroundResource(android.R.color.transparent);
        }
        mBottomSheetDialog.setCancelable(false);

        final RecyclerView recBrand = sheetView.findViewById(R.id.rec_brand);
        ImageView img_cancel = sheetView.findViewById(R.id.img_cancel);
        TextView tv_clear_filter = sheetView.findViewById(R.id.tv_clear_filter);
        recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature));
        recBrand.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));

        cardSignature = sheetView.findViewById(R.id.card_signature);
        cardBrand = sheetView.findViewById(R.id.card_brand);
        cardSubBrand = sheetView.findViewById(R.id.card_sub_brand);
        cardReference = sheetView.findViewById(R.id.card_reference);

        cardSignature.setOnClickListener(this);
        cardBrand.setOnClickListener(this);
        cardSubBrand.setOnClickListener(this);
        cardReference.setOnClickListener(this);

        cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));

        if (selectedSignature != null) {
            (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.VISIBLE);
        }
        if (selectedBrand != null) {
            (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.VISIBLE);
        }
        if (selectedSubBrand != null) {
            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.VISIBLE);
        }
        if (selectedReference != null) {
            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.VISIBLE);
        }

        img_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.cancel();
            }
        });

        tv_clear_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFilter(CLEAR_FILTER);
                selectedSignature = null;
                selectedBrand = null;
                selectedSubBrand = null;
                selectedReference = null;

                cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
                cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
                cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
                cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));

                (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE);
                (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE);
                (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
                (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);

                db.open();
                brandList = db.getsub_brand_name(counterGroupId, "BrandName", false);
                db.open();
                subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false);
                db.open();
                referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false);
                db.open();
                signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false);

                Objects.requireNonNull(recBrand.getAdapter()).notifyDataSetChanged();
            }
        });

        mBottomSheetDialog.show();

        return sheetView;
    }

    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;
        String type;

        public ValueAdapter(Context context, List<ProductMaster> data, String type) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.type = type;
        }

        @NonNull
        @Override
        public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.item_filter, parent, false);
            return new ValueAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ValueAdapter.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);

            final boolean[] selected = {false};
            final int[] filterId = {0};

            switch (type) {

                case CommonString.Signature:
                    if (selectedSignature != null && selectedSignature == current) {
                        selected[0] = true;
                    }

                    break;

                case CommonString.Brand:
                    if (selectedBrand != null && selectedBrand == current) {
                        selected[0] = true;
                    }

                    break;

                case CommonString.SubBrand:
                    if (selectedSubBrand != null && selectedSubBrand == current) {
                        selected[0] = true;
                    }

                    break;

                case CommonString.Reference:
                    if (selectedReference != null && selectedReference == current) {
                        selected[0] = true;
                    }

                    break;
            }

            holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getBrandName()));

            holder.tv_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    et_search.setText("");
                    switch (type) {
                        case CommonString.Signature:
                            selectedSignature = current;
                            filterId[0] = R.id.img_filter_signature;

                            //clear other sub filters--
                            selectedBrand = null;
                            selectedSubBrand = null;
                            selectedReference = null;

                            (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE);
                            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
                            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
                            //--

                            setFilter(FILTER_FOR_SIGNATURE);
                            db.open();
                            brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false);
                            db.open();
                            subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false);
                            db.open();
                            referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false);

                            break;
                        case CommonString.Brand:
                            selectedBrand = current;
                            filterId[0] = R.id.img_filter_brand;

                            //clear other sub filters--
                            selectedSubBrand = null;
                            selectedReference = null;

                            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
                            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
                            //--

                            setFilter(FILTER_FOR_BRAND);
                            db.open();
                            subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false);
                            db.open();
                            referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false);
                            break;
                        case CommonString.SubBrand:
                            selectedSubBrand = current;
                            filterId[0] = R.id.img_filter_sub_brand;
                            //clear other sub filters--
                            selectedReference = null;
                            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
                            setFilter(FILTER_FOR_SUB_BRAND);
                            db.open();
                            referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false);
                            break;

                        case CommonString.Reference:
                            selectedReference = current;
                            filterId[0] = R.id.img_filter_reference;

                            setFilter(FILTER_FOR_REFERENCE);
                            break;
                    }

                    RecyclerView recSubBrand = sheetView.findViewById(R.id.rec_brand);
                    recSubBrand.getAdapter().notifyDataSetChanged();
                    //show filter icon on filter selected
                    (sheetView.findViewById(filterId[0])).setVisibility(View.VISIBLE);
                }
            });

            if (selected[0]) {
                holder.card.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
            } else {
                holder.card.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv_item;
            CardView card;

            public MyViewHolder(View itemView) {
                super(itemView);
                tv_item = (TextView) itemView.findViewById(R.id.tv_item);
                card = (CardView) itemView.findViewById(R.id.item_card);
            }
        }
    }

    void setFilterSelected(View sheetView, String type) {
        CardView cardSignature, cardBrand, cardSubBrand, cardReference;
        cardSignature = sheetView.findViewById(R.id.card_signature);
        cardBrand = sheetView.findViewById(R.id.card_brand);
        cardSubBrand = sheetView.findViewById(R.id.card_sub_brand);
        cardReference = sheetView.findViewById(R.id.card_reference);

        cardSignature.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
        cardBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
        cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));
        cardReference.setCardBackgroundColor(getResources().getColor(R.color.grey_dark_background));

        switch (type) {
            case CommonString.Signature:
                cardSignature.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
            case CommonString.Brand:
                cardBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
            case CommonString.SubBrand:
                cardSubBrand.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
            case CommonString.Reference:
                cardReference.setCardBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                break;
        }
    }

    public ArrayList<ProductMaster> filterListForSignature(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSignatureName().equalsIgnoreCase(text)) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForSubBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSubBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName())) && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName()))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForReference(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getReferenceName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))
                    && (selectedBrand == null || object.getBrandName().equalsIgnoreCase(selectedBrand.getBrandName())) && (selectedSubBrand == null || object.getSubBrandName().equalsIgnoreCase(selectedSubBrand.getBrandName()))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public void setFilter(int filterType) {
        if (filterType == FILTER_FOR_SIGNATURE) {
            listAdapter = new ExpandableListAdapter(context, filterListForSignature(listDataHeader, selectedSignature.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_BRAND) {
            listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, selectedBrand.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_SUB_BRAND) {
            listAdapter = new ExpandableListAdapter(context, filterListForSubBrand(listDataHeader, selectedSubBrand.getBrandName()), listDataChild);
        } else if (filterType == FILTER_FOR_REFERENCE) {
            listAdapter = new ExpandableListAdapter(context, filterListForReference(listDataHeader, selectedReference.getBrandName()), listDataChild);
        } else {
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        }

        lvExp_stock_check.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.filter_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @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) {
            isChanged();

        } else if (id == R.id.filter_data) {
            sheetView = showFilterBottomSheet();
        }

        return super.onOptionsItemSelected(item);
    }

    private void openScanner() {
        IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) context);
        intentIntegrator.setBeepEnabled(true);
        intentIntegrator.setOrientationLocked(false);
        intentIntegrator.setPrompt("Scan the barcode or QR code to get the data");
        intentIntegrator.initiateScan();
    }


    public void setScanFilter(List<ProductMaster> scanList) {

        HashMap<ProductMaster, List<ProductMaster>> filterChildHashMap = new HashMap<>();

        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            ProductMaster parent = listDataHeader.get(i);
            List<ProductMaster> listChild = listDataChild.get(parent);
            List<ProductMaster> listFilterChild = new ArrayList<>();
            for (int j = 0; j < listChild.size(); j++) {
                if (containsProduct(scanList, listChild.get(j))) {
                    listFilterChild.add(listChild.get(j));
                } else {
                    continue;
                }
            }

            if (listFilterChild.size() > 0) {
                filterList.add(parent);
                filterChildHashMap.put(parent, listFilterChild);

            }

        }

        ExpandableListAdapter listAdapter1 = new ExpandableListAdapter(context, filterList, filterChildHashMap);
        lvExp_stock_check.setAdapter(listAdapter1);

        for (int i = 0; i < listAdapter1.getGroupCount(); i++) {
            lvExp_stock_check.expandGroup(i);
        }

        listAdapter1.notifyDataSetChanged();


    }

    boolean containsProduct(List<ProductMaster> scanList, ProductMaster obj) {
        boolean contains = false;

        for (int i = 0; i < scanList.size(); i++) {
            if (scanList.get(i).getProductId().equals(obj.getProductId())) {
                contains = true;
                break;
            }
        }

        return contains;
    }

    void clearFilters() {
        et_search.setText("");

        setFilter(CLEAR_FILTER);
        selectedSignature = null;
        selectedBrand = null;
        selectedSubBrand = null;
        selectedReference = null;

        if (sheetView != null) {
            (sheetView.findViewById(R.id.img_filter_signature)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_brand)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_sub_brand)).setVisibility(View.GONE);
            (sheetView.findViewById(R.id.img_filter_reference)).setVisibility(View.GONE);
        }

        db.open();
        brandList = db.getsub_brand_name(counterGroupId, "BrandName", false);
        db.open();
        subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false);
        db.open();
        referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false);
        db.open();
        signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false);
    }

    public void uploadData() {
        //download service
        // Intent intent = new Intent(context, Downloader.class);
        SaleableGetterSetter stock = new SaleableGetterSetter();
        ArrayList<ProductMaster> data = new ArrayList<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).isSelected()) {
                    list.get(j).setImagePath(listDataHeader.get(i).getImagePath());
                    data.add(list.get(j));
                }
            }
        }

        if (data.size() > 0) {
            stock.setProductList(data);
            String uuid = CommonFunctions.getUUID(context);
            stock.setTransactionId(uuid);
            db.open();
            db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.DAMAGE, stock, "Regular_Stock");

            /*intent.putExtra(CommonString.DAMAGE, stock);
            String status = null;
            intent.putExtra(CommonString.KEY_STATUS, status);
            Downloader.enqueueWork(context, intent);*/
            dialog.cancel();
            CommonFunctions.call_upload(context);
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            DamagedActivity.this.finish();
        }
    }

    private Dialog dialog;
    ProgressBar pb;

    class LoadAsync extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            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(Void... voids) {
            //validateUIData();
            prepareListData();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.cancel();
            recSubAxe.setLayoutManager(new GridLayoutManager(DamagedActivity.this, 3));
            subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature);
            recSubAxe.setAdapter(subAxeValueAdapter);
            recSubAxe.getAdapter().notifyDataSetChanged();

            //validate_spin_ui_data();
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
            lvExp_stock_check.setAdapter(listAdapter);

            db.open();
            JourneyPlan jcp = db.getJCP();
            if (jcp != null) {
                counterGroupId = jcp.getCounterGroupId().toString();
            } else {
                counterGroupId = "1";
            }

            if (damaged_category_str != null && damaged_category_str.equals("0")) {
                if (listDataHeader.size() > 0) {
                    rl_total_qty.setVisibility(View.VISIBLE);
                    txt_total_qty.setText("Return Total QTY : " + calculate_total_qty());
                    txt_total_value.setText("Return Total Values : " + calculate_total_sale_value());
                } else {
                    rl_total_qty.setVisibility(View.GONE);
                }
            } else if (damaged_category_str != null && damaged_category_str.equals("1")) {
                rl_total_qty.setVisibility(View.GONE);
            }

            super.onPostExecute(aVoid);
        }
    }

    void dialogFinalSubmit(final boolean returntodistr) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(DamagedActivity.this);
        builder.setTitle(R.string.parinaam);
        if (returntodistr) {
            builder.setMessage(getResources().getString(R.string.want_to_final_savedamage));
        } else {
            builder.setMessage(getResources().getString(R.string.want_to_final_damage_save));
        }
        builder.setCancelable(false)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog1, int id) {
                        show_dialog_for_final_submit(context, returntodistr);

                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

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

    private class SubAxeValueAdapter extends RecyclerView.Adapter<SubAxeValueAdapter.MyViewHolder> {
        private LayoutInflater inflator;
        List<ProductMaster> data;
        String type;

        public String getType() {
            return type;
        }

        private SubAxeValueAdapter(Context context, List<ProductMaster> data, String type) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.type = type;
        }

        @NonNull
        @Override
        public SubAxeValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.item_filter, parent, false);
            return new SubAxeValueAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);

            holder.tv_item.setText(CommonFunctions.capitalizeFirstLetter(current.getSubAxeName()));

            holder.tv_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    et_search.setText("");
                    listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, current.getSubAxeName()), listDataChild);
                    lvExp_stock_check.setAdapter(listAdapter);
                    listAdapter.notifyDataSetChanged();

                    current.setSelected(true);
                    selectedSubAxe = current.getSubAxeName();
                    subAxeValueAdapter.notifyDataSetChanged();

                    JourneyPlan jcp = db.getJCP();
                    if (jcp != null) {
                        db.open();
                        brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe);
                        db.open();
                        subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe);
                        db.open();
                        referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe);
                        db.open();
                        signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe);
                    } else {
                        db.open();
                        brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe);
                        db.open();
                        subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe);
                        db.open();
                        referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe);
                        db.open();
                        signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe);
                    }
                }
            });

            if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) {
                holder.card.setCardBackgroundColor(getColor(R.color.dashboard_ach));
            } else {
                holder.card.setCardBackgroundColor(getColor(R.color.grey_dark_background));
            }

        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv_item;
            CardView card;

            public MyViewHolder(View itemView) {
                super(itemView);
                tv_item = (TextView) itemView.findViewById(R.id.tv_item);
                card = (CardView) itemView.findViewById(R.id.item_card);

            }
        }
    }

    public ArrayList<ProductMaster> filterListForSubAxe(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSubAxeName().equalsIgnoreCase(text)) {
                filterList.add(object);
            } else {
                continue;
            }
        }

        return filterList;
    }

    private int calculate_total_qty() {
        int total_return_qty = 0;
        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
                for (int j = 0; j < list.size(); j++) {

                    total_return_qty = total_return_qty + (list.get(j).getStock());
                }
            }
        }

        return total_return_qty;
    }

    private int calculate_total_sale_value() {
        int total_sale_value = 0;
        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                List<ProductMaster> list = listDataChild.get(listDataHeader.get(i));
                for (int j = 0; j < list.size(); j++) {
                    total_sale_value = total_sale_value + (list.get(j).getStock() * list.get(j).getMrp());
                }
            }
        }

        return total_sale_value;
    }

}
