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.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;

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 android.os.Bundle;

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.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.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.journeyapps.barcodescanner.CaptureActivity;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.adapter.ReasonSpinnerAdapter;
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.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonStockReason;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;

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

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 FilledRegularStockDataActivity extends AppCompatActivity implements View.OnClickListener {
    Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin;
    ArrayList<ProductMaster> brandList = new ArrayList<>();
    ArrayList<ProductMaster> subBrandList = new ArrayList<>();
    ArrayList<ProductMaster> referenceList = new ArrayList<>();
    ArrayList<ProductMaster> signatureList = new ArrayList<>();
    ExpandableListView lvExp_stock_check;
    FloatingActionButton fab_save, fab_draft;
    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;
    boolean regularStockFlag = false;
    View sheetView;
    ProductMaster selectedSignature, selectedBrand, selectedSubBrand, selectedReference;
    ImageView img_scan, img_clear_subaxe, img_unfilled;
    boolean flagScan = true;
    String counterGroupId;
    RecyclerView recSubAxe;
    String selectedSubAxe = "", activity_name = "";
    SubAxeValueAdapter subAxeValueAdapter;
    ArrayList<ProductMaster> listSubAxe;
    CardView card_view_only;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filled_regular_stock_data);
        context = this;
        ((FilledRegularStockDataActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();

        activity_name = getIntent().getStringExtra(CommonString.KEY_ACTIVITY);

        validateUIData();
        new LoadAsync().execute();
    }

    JourneyPlan jcp;

    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, "");
        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);
        if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) {
            setTitle("Filled Stock Check - " + visit_date);
        } else {
            setTitle("Filled Tester Check - " + visit_date);
        }

        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);
        fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab);
        et_search = (EditText) findViewById(R.id.et_search);
        img_scan = (ImageView) findViewById(R.id.img_scan);
        img_unfilled = (ImageView) findViewById(R.id.img_unfilled);
        img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe);
        ImageView img_filter = (ImageView) findViewById(R.id.img_filter);
        recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        card_view_only = (CardView) findViewById(R.id.card_view_only);
        fab_save.setOnClickListener(this);
        fab_draft.setOnClickListener(this);
        db.open();

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

        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_scan.setOnClickListener(this);
        ///changes icon
        img_unfilled.setOnClickListener(this);
        img_clear_subaxe.setOnClickListener(this);
        img_unfilled.setVisibility(View.GONE);

        String status = "";
        if (activity_name != null && !activity_name.equals("") && activity_name.equalsIgnoreCase("StockCheck")) {
            status = db.getStatus(CommonString.KEY_SaleableStatus, counter_id);
        } else {
            status = db.getStatus(CommonString.KEY_TesterStatus, counter_id);
        }

        //if regular stock need to be captured after First stock capture
        if (status != null && !status.equals("") && status.equalsIgnoreCase("Complete")) {
            fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.save_icon));
            regularStockFlag = true;
            fab_draft.hide();
        }

        card_view_only.setVisibility(View.VISIBLE);
    }

    View showFilterBottomSheet() {
        final CardView cardSignature, cardBrand, cardSubBrand, cardReference;
        final BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this);
        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) {
                clearFilters();
                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));
                ValueAdapter adapter = (ValueAdapter) recBrand.getAdapter();
                String type = adapter.getType();
                ArrayList<ProductMaster> list = new ArrayList<>();
                switch (type) {
                    case CommonString.Signature:
                        list = signatureList;
                        break;
                    case CommonString.Brand:
                        list = brandList;
                        break;
                    case CommonString.SubBrand:
                        list = subBrandList;
                        break;
                    case CommonString.Reference:
                        list = referenceList;
                        break;
                }
                recBrand.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true));
                recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature));
                recBrand.getAdapter().notifyDataSetChanged();

            }
        });

        mBottomSheetDialog.show();

        return sheetView;
    }

    private void prepareListData() {
        db.open();
        jcp = db.getJCP();
        if (jcp != null) {
            listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true);
        } else {
            listSubAxe = db.getSubAxe("1", true);
        }

        listDataHeader = new ArrayList<>();
        listDataChild = new HashMap<>();

        //inserted data
        db.open();
        db.open();
        jcp = db.getJCP();
        if (jcp != null) {
            listDataHeader = db.getFunctionforFilledName(jcp.getCounterGroupId().toString(), selectedSubAxe, activity_name);
        } else {
            listDataHeader = db.getStockSignatureBrandSubBrandReferenceforfilled("1", activity_name);
        }

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


        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                db.open();
                JourneyPlan jcp = db.getJCP();
                if (jcp != null) {
                    db.open();
                    childStockList = db.getDefaultStockOnFunctionDataforFilled(listDataHeader.get(i).getNuanceName(), counter_id, activity_name);
                } else {
                    childStockList = db.getDefaultStockOnFunctionDataforFilled(listDataHeader.get(i).getNuanceName(), counter_id, activity_name);
                }

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

        }

    }

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

    @Override
    public void onClick(View view) {

        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_unfilled) {
            setUnFilledFilter(listAdapter.get_listDataHeader(), listAdapter.get_listDataChild());
        } 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);
            subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe);
            referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe);
            signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe);
        }
    }


    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> filterListForBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {

            if (object.getBrandName().equalsIgnoreCase(text) && (selectedSignature == null || object.getSignatureName().equalsIgnoreCase(selectedSignature.getBrandName()))) {
                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 ArrayList<ProductMaster> filterListForAxe(List<ProductMaster> originalList, String text, String brandName) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForSubAxe(List<ProductMaster> originalList, String text, String brandName, String axeName) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) {
                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;
        }

        @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_stock_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.reasonSpinner = convertView.findViewById(R.id.reason_spinner);
                holder.reasonLayout = convertView.findViewById(R.id.reason_layout);
                holder.et_stock = convertView.findViewById(R.id.et_stock);
                convertView.setTag(holder);


            } else {

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

            holder.stock_img_minus.setVisibility(View.INVISIBLE);
            holder.stock_img_minus.setId(childPosition);

            holder.stock_img_plus.setVisibility(View.INVISIBLE);
            holder.stock_img_plus.setId(childPosition);

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

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


            holder.stock_img_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                    if (!regularStockFlag) {
                        String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", "");
                        if (!stot.equals("")) {
                            int st = Integer.parseInt(stot);
                            childText.setStock(st);
                        }
                    }

                    int stock = childText.getStock();
                    int receivedStock = childText.getStock_receive();

                    ++stock;

                    if (regularStockFlag) {
                        if (receivedStock >= stock) {
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                            if (receivedStock == stock) {
                                finalHolder.reasonLayout.setVisibility(View.GONE);
                                finalHolder.reasonSpinner.setSelection(0);
                                childText.setReasonId(0);
                            }
                        } else {
                            AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock");
                        }
                    } else {
                        if (receivedStock == -1) {
                            childText.setStock_receive(0);
                        }
                        childText.setStock(stock);
                        isDataAdded = true;
                        childText.setSelected(true);
                    }

                }
            });


            holder.stock_img_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //listAdapter.notifyDataSetChanged();
                    ((ExpandableListAdapter) lvExp_stock_check.getExpandableListAdapter()).notifyDataSetChanged();
                    if (!regularStockFlag) {
                        String stot = finalHolder.et_stock.getText().toString().trim().replaceFirst("^0+(?!$)", "");
                        if (!stot.equals("")) {
                            int st = Integer.parseInt(stot);
                            childText.setStock(st);
                        }
                    }

                    int stock = childText.getStock();
                    int receivedStock = childText.getStock_receive();
                    --stock;
                    if (stock >= 0) {
                        if (regularStockFlag && stock < receivedStock) {
                            finalHolder.reasonLayout.setVisibility(View.VISIBLE);
                        }

                        childText.setStock(stock);
                        isDataAdded = true;
                        childText.setSelected(true);

                    } else {
                        AlertandMessages.showToastMsg(context, "Stock cannot be less than 0");
                    }

                }
            });

            holder.et_stock.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        final EditText caption = (EditText) v;
                        String stock = caption.getText().toString().replaceFirst("^0+(?!$)", "");
                        if (!stock.equals("")) {
                            childText.setStock(Integer.parseInt(stock));
                            isDataAdded = true;
                            childText.setSelected(true);
                        } else {
                            childText.setStock(0);
                        }
                    }
                }
            });

            ArrayList<MasterNonStockReason> reasonList = new ArrayList<>();
            db.open();
            reasonList = db.getReasonData(true);
            holder.reasonSpinner.setAdapter(new ReasonSpinnerAdapter(_context, R.layout.spinner_text_view, reasonList));
            final ArrayList<MasterNonStockReason> finalReasonList = reasonList;
            holder.reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                    if (pos != 0) {
                        MasterNonStockReason obj = finalReasonList.get(pos);
                        childText.setReasonId(obj.getReasonId());
                    } else {
                        childText.setReasonId(0);
                    }
                }

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

                }
            });


            if (!finalReasonList.isEmpty()) {
                for (int i = 0; i < finalReasonList.size(); i++) {
                    if (finalReasonList.get(i).getReasonId() == childText.getReasonId()) {
                        holder.reasonSpinner.setSelection(i);
                        break;
                    }
                }
            }


            int stock = childText.getStock();
            if (!childText.isSelected() && childText.getStock() == 0) {
                stock = childText.getStock_receive();
                childText.setStock(stock);
            }

            if (childText.getStock() < childText.getStock_receive()) {
                if (regularStockFlag) {
                    finalHolder.reasonLayout.setVisibility(View.VISIBLE);
                    finalHolder.reasonLayout.setId(childPosition);
                }
            } else {
                finalHolder.reasonLayout.setVisibility(View.GONE);
                finalHolder.reasonLayout.setId(childPosition);
            }


            holder.ed_Stock.setText("Stock - " + stock + "");
            holder.ed_Stock.setId(childPosition);

            holder.et_stock.setVisibility(View.GONE);
            holder.ed_Stock.setVisibility(View.VISIBLE);

            holder.mrp.setText(" MRP = " + childText.getMrp() + "");
            holder.mrp.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.setEnabled(false);

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

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

            lblListHeader.setText(headerTitle.getNuanceName());
            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;
        Button stock_img_plus, stock_img_minus;
        CardView cardView;
        Spinner reasonSpinner;
        LinearLayout reasonLayout;
        EditText et_stock;
    }

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


    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 if (filterType == FILTER_FOR_AXE) {
            listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild);
        } else if (filterType == FILTER_FOR_SUBAXE) {
            listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild);
        } else {
            listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild);
        }

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

    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 FILTER_FOR_AXE = 2;
    final int FILTER_FOR_SUBAXE = 3;
    final int CLEAR_FILTER = 0;

    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 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 isDataAdded = false;

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

    void isChanged() {
        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;
                            globalHeaderObject.setImagePath(_pathforcheck);
                            groupPositionGlobal = -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);
                    }

                    //test("Ean Code", result.getContents());
                    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);
    }


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

        public String getType() {
            return type;
        }

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

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

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onBindViewHolder(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(current.getBrandName());

            holder.card.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);
                            //--

                            db.open();
                            setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature);
                            brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe);
                            subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe);
                            referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", current.getBrandName(), null, null, false, selectedSubAxe);

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

                            setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Brand);
                            //setFilter(FILTER_FOR_BRAND);
                            db.open();
                            subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", "", current.getBrandName(), null, false, selectedSubAxe);
                            referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", current.getBrandName(), null, false, selectedSubAxe);

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


                            setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.SubBrand);
                            //setFilter(FILTER_FOR_SUB_BRAND);
                            db.open();
                            referenceList = db.getSubBrandOrReference(counterGroupId, "ReferenceName", "", null, current.getBrandName(), false, selectedSubAxe);
                            break;
                        case CommonString.Reference:
                            selectedReference = current;
                            filterId[0] = R.id.img_filter_reference;
                            setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.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(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);

            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.filter_menu_filled, 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.setCaptureActivity(CaptureActivity.class);
        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, selectedSubAxe);
        subBrandList = db.getsub_brand_name(counterGroupId, "SubBrandName", false, selectedSubAxe);
        referenceList = db.getsub_brand_name(counterGroupId, "ReferenceName", false, selectedSubAxe);
        signatureList = db.getsub_brand_name(counterGroupId, "SignatureName", false, selectedSubAxe);
    }

    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) {
            prepareListData();
            //validate_spin_ui_data();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            dialog.cancel();

            recSubAxe.setLayoutManager(new GridLayoutManager(context, 3));
            subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe, CommonString.Signature);
            recSubAxe.setAdapter(subAxeValueAdapter);

            recSubAxe.getAdapter().notifyDataSetChanged();

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

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

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

                @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();
                }
            });
            db.open();
            JourneyPlan jcp = db.getJCP();
            if (jcp != null) {
                counterGroupId = jcp.getCounterGroupId().toString();
            } else {
                counterGroupId = "1";
            }

            super.onPostExecute(aVoid);
        }
    }


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

        public String getType() {
            return type;
        }

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

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

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


            holder.tv_item.setText(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();
                    //setExpandableDataForSubAxe(current.getSubAxeName());
                    current.setSelected(true);
                    selectedSubAxe = current.getSubAxeName();
                    subAxeValueAdapter.notifyDataSetChanged();
                    db.open();
                    jcp = db.getJCP();
                    if (jcp != null) {
                        brandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "BrandName", false, selectedSubAxe);
                        subBrandList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SubBrandName", false, selectedSubAxe);
                        referenceList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "ReferenceName", false, selectedSubAxe);
                        signatureList = db.getsub_brand_name(jcp.getCounterGroupId().toString(), "SignatureName", false, selectedSubAxe);
                    } else {
                        brandList = db.getsub_brand_name("1", "BrandName", false, selectedSubAxe);
                        subBrandList = db.getsub_brand_name("1", "SubBrandName", false, selectedSubAxe);
                        referenceList = db.getsub_brand_name("1", "ReferenceName", false, selectedSubAxe);
                        signatureList = db.getsub_brand_name("1", "SignatureName", false, selectedSubAxe);
                    }
                }
            });

            //if (current.isSelected()) {
            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;
    }

    public void setBottomFilter(List<ProductMaster> originalList, String text, HashMap<ProductMaster,
            List<ProductMaster>> listDataChild, String type) {

        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++) {

                switch (type) {
                    case CommonString.Signature:
                        if (listChild.get(j).getSignatureName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                    case CommonString.Brand:
                        if (listChild.get(j).getBrandName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                    case CommonString.SubBrand:
                        if (listChild.get(j).getSubBrandName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                    case CommonString.Reference:
                        if (listChild.get(j).getReferenceName().equalsIgnoreCase(text)) {
                            listFilterChild.add(listChild.get(j));
                        }
                        break;
                }

            }

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

            }

        }

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

    public void setUnFilledFilter(List<ProductMaster> originalList, 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).getStock() == -1) {
                    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();
    }

}
