package com.cpm.lorealbaMabeline.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.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.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.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.gson.JsonObject;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gettersetter.SaleableGetterSetter;
import com.cpm.lorealbaMabeline.gsonGetterSetter.JourneyPlan;
import com.cpm.lorealbaMabeline.gsonGetterSetter.ProductMaster;
import com.cpm.lorealbaMabeline.retrofit.PostApi;

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

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

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

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

public class TesterStockActivity extends AppCompatActivity implements View.OnClickListener {
    Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin;
    ArrayList<ProductMaster> brandList = 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;
    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;
    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;

    boolean regularStockFlag = false, check_flag = true;
    ImageView img_scan;

    boolean flagScan = true;
    private String counterGroupId;

    RecyclerView recSubAxe;

    String selectedSubAxe = "";
    SubAxeValueAdapter subAxeValueAdapter;
    ArrayList<ProductMaster> listSubAxe;
    ImageView img_clear_subaxe;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tester_stock);
        context = this;
        ((TesterStockActivity) 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();
            }
        });

    }

    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);
        setTitle("Tester Stock - " + 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);
        et_search = (EditText) findViewById(R.id.et_search);
        fab_save = (FloatingActionButton) findViewById(R.id.save_fab);
        fab_draft = (FloatingActionButton) findViewById(R.id.draft_fab);
        img_scan = (ImageView) findViewById(R.id.img_scan);
        recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        img_clear_subaxe = (ImageView) findViewById(R.id.img_clear_subaxe);

        fab_save.setOnClickListener(this);
        fab_draft.setOnClickListener(this);
        img_scan.setOnClickListener(this);
        img_clear_subaxe.setOnClickListener(this);
        ImageView img_unfilled = (ImageView) findViewById(R.id.img_unfilled);
        img_unfilled.setVisibility(View.INVISIBLE);
        db.open();
        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_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sheetView = showFilterBottomSheet();
            }
        });

        db.open();
        String 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")) {
            regularStockFlag = true;
            fab_draft.hide();
        }
    }

    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();
        jcp = db.getJCP();
        if (jcp != null) {
            db.open();
            listSubAxe = db.getSubAxe(jcp.getCounterGroupId().toString(), true);
        } else {
            listSubAxe = db.getSubAxe("1", true);
        }

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

        //for filter bottom sheet
        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);
            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);
        }

        //inserted data
        db.open();
        listDataHeader = db.getTesterHeaderInsertedData(visit_date, regularStockFlag);
        if (listDataHeader.size() == 0) {
            if (jcp != null) {
                db.open();
                listDataHeader = db.getFunctionName(jcp.getCounterGroupId().toString(), selectedSubAxe, regularStockFlag, "TesterBalance", counter_id, visit_date);
            } else {
                db.open();
                listDataHeader = db.getStockSignatureBrandSubBrandReference("1", false, regularStockFlag, "TesterBalance");
            }
        }


        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                db.open();
                childStockList = db.getDefaultStockOnFunctionData(listDataHeader.get(i).getNuanceName(), CommonString.KEY_TesterBalance, counter_id, regularStockFlag, visit_date);
                listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data
            }
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        if (id == R.id.save_fab) {
            db.open();
            lvExp_stock_check.clearFocus();
            lvExp_stock_check.invalidateViews();
            if (regularStockFlag) {
                dialogFinalSubmit(listDataChild, listDataHeader);
            } else {
                dialogFinalSubmit(listDataChild, listDataHeader);
            }

        } else if (id == R.id.draft_fab) {
            lvExp_stock_check.clearFocus();
            lvExp_stock_check.invalidateViews();
            new InsertAsync().execute(false);

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

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

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

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

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

        } else if (id == 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);
        }
    }


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

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

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

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

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


            } else {

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

            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 (stock != 0 && stock > 3) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam);
                        builder.setMessage("You have entered Tester Stock greater than 3. Please confirm is the value is correct")
                                .setCancelable(false)
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.dismiss();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }


                    if (regularStockFlag) {
                        if (receivedStock >= stock) {
                            childText.setStock(stock);
                            isDataAdded = true;
                            childText.setSelected(true);
                        } else {
                            AlertandMessages.showToastMsg(context, "Stock cannot be greater than Received Stock");
                        }
                    } else {
                        childText.setStock(stock);
                        isDataAdded = true;
                        childText.setSelected(true);
                    }
                }
            });

            holder.stock_img_minus.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();
                    --stock;

                    if (stock >= 0) {
                        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);
                        if (childText.getStock() != 0 && childText.getStock() > 3) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam);
                            builder.setMessage("You have entered Tester Stock greater than 3. Please confirm is the value is correct")
                                    .setCancelable(false)
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                            AlertDialog alert = builder.create();
                            alert.show();
                        }
                    } else {
                        childText.setStock(0);
                    }

                    //  }

                }
            });

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

            if (regularStockFlag) {
                holder.ed_Stock.setText(stock + "");
                holder.ed_Stock.setId(childPosition);

                holder.et_stock.setVisibility(View.GONE);
                holder.ed_Stock.setVisibility(View.VISIBLE);
            } else {

                if (stock == -1) {
                    holder.et_stock.setText("");
                } else {
                    holder.et_stock.setText(stock + "");
                }

                holder.et_stock.setId(childPosition);

                holder.ed_Stock.setVisibility(View.GONE);
                holder.et_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.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    groupPositionGlobal = groupPosition;
                    globalHeaderObject = headerTitle;
                    _pathforcheck = counter_id + "_tester_stock_img_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(TesterStockActivity.this, _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;
        EditText et_stock;
    }


    @Override
    public void onDestroy() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        super.onDestroy();
    }

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

    @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.equals("")) {
                        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);
                    }

                    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() {
        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.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
        recBrand.setAdapter(new ValueAdapter(context, signatureList, CommonString.Signature));

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

                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(TesterStockActivity.this, LinearLayoutManager.VERTICAL, true));
                recBrand.setAdapter(new ValueAdapter(context, list, CommonString.Signature));
                recBrand.getAdapter().notifyDataSetChanged();

            }
        });

        mBottomSheetDialog.show();

        return sheetView;
    }

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

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

        public String getType() {
            return 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);
                            //--

                            setBottomFilter(listAdapter.get_listDataHeader(), current.getBrandName(), listAdapter.get_listDataChild(), CommonString.Signature);
                            db.open();
                            brandList = db.getSubBrandOrReference(counterGroupId, "BrandName", current.getBrandName(), null, null, false, selectedSubAxe);
                            db.open();
                            subBrandList = db.getSubBrandOrReference(counterGroupId, "SubBrandName", current.getBrandName(), null, null, false, selectedSubAxe);
                            db.open();
                            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);
                            db.open();
                            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(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, filterListForSubAxe(listDataHeader, selectedSubAxe), listDataChild);
        }

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


    public void uploadData(boolean finalFlag) {
        //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++) {
                //for final - complete data upload
                if (finalFlag) {
                    list.get(j).setImagePath(listDataHeader.get(i).getImagePath());
                    data.add(list.get(j));
                } else {
                    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);
            ////changes by jeevan insert transaction for future use and handle master traction
            if (regularStockFlag) {
                db.open();
                db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.TESTER, stock, "Regular_Stock");
            } else {
                if (finalFlag) {
                    db.open();
                    db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.TESTER, stock, "FirstTime_Stock_Comp");
                } else {
                    db.open();
                    db.insertStockTransactionMasterData(counter_id, visit_date, username, CommonString.TESTER, stock, "FirstTime_Stock_Draft");
                }
            }

            dialog.cancel();
            CommonFunctions.call_upload(context);
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            TesterStockActivity.this.finish();


            /*//for complete upload
            if (finalFlag) {
                if (CommonFunctions.checkNetIsAvailable(context)) {
                    int endIndex = 0;
                    int startIndex = endIndex;
                    if (startIndex + 200 < stock.getProductList().size()) {
                        endIndex = startIndex + 200;
                    } else {
                        endIndex = stock.getProductList().size();
                    }

                    UploadStockRecursive(CommonString.KEY_COMPLETE, 0, endIndex, stock);
                }
            } else {
                intent.putExtra(CommonString.TESTER, stock);
                String status;
                if (regularStockFlag) {
                    status = null;
                } else {
                    if (finalFlag) {
                        status = CommonString.KEY_COMPLETE;
                    } else {
                        status = CommonString.KEY_DRAFT;
                    }
                }
                intent.putExtra(CommonString.KEY_STATUS, status);
                Downloader.enqueueWork(TesterStockActivity.this, intent);
                dialog.cancel();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                TesterStockActivity.this.finish();
            }*/
        }
    }

    void dialogFinalSubmit(final HashMap<ProductMaster, List<ProductMaster>> listDataChild, final ArrayList<ProductMaster> listDataHeader) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(TesterStockActivity.this);
        builder.setTitle("Parinaam");
        builder.setMessage(getResources().getString(R.string.want_to_final_save)).setCancelable(false)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        show_dialog_for_final_submit(context);
                    }
                })
                .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 void show_dialog_for_final_submit(final Context context) {
        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);

        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_save_dialog.dismiss();
                    if (regularStockFlag) {
                        new InsertAsync().execute(false);
                    } else {
                        new InsertAsync().execute(true);
                    }
                }
            }
        });


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

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

    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(TesterStockActivity.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) {
                db.open();
                counterGroupId = jcp.getCounterGroupId().toString();
            } else {
                counterGroupId = "1";
            }

            super.onPostExecute(aVoid);
        }
    }

    public class SubAxeValueAdapter extends RecyclerView.Adapter<SubAxeValueAdapter.MyViewHolder> {
        private LayoutInflater inflator;
        List<ProductMaster> data;
        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(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();
                    //setExpandableDataForSubAxe(current.getSubAxeName());
                    current.setSelected(true);
                    selectedSubAxe = current.getSubAxeName();
                    subAxeValueAdapter.notifyDataSetChanged();

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


    }

    private void UploadStockRecursive(final String status, final int startIndex, final int endIndex, final SaleableGetterSetter stock) {
        try {

            JSONArray topUpArray = new JSONArray();
            String key = "TesterData";
            int mid = 0;
            if (stock != null) {

                if (jcp != null) {
                    mid = jcp.getMID();
                }
                for (int j = startIndex; j < endIndex; j++) {
                    JSONObject obj = new JSONObject();
                    obj.put("ProductId", stock.getProductList().get(j).getProductId());
                    obj.put("MID", mid);
                    obj.put("TranId", stock.getTransactionId());
                    obj.put("UserId", username);
                    obj.put("CounterId", counter_id);

                    if (status != null) {
                        int stk = stock.getProductList().get(j).getStock();
                        if (stk == -1) {
                            stk = 0;
                        }

                        obj.put("STOCK", stk);
                        obj.put("Status", status);
                        //different key for first time data
                        key = "TesterFData";
                    } else {
                        obj.put("STOCK", stock.getProductList().get(j).getStock_receive() - stock.getProductList().get(j).getStock());
                    }

                    topUpArray.put(obj);
                }
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("MID", mid);
            jsonObject.put("Keys", key);
            jsonObject.put("JsonData", topUpArray.toString());
            jsonObject.put("UserId", username);

            String jsonString = jsonObject.toString();

            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).connectTimeout(20, TimeUnit.SECONDS).build();
            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<JsonObject> call = api.getGeotag(jsonData);
            call.enqueue(new Callback<JsonObject>() {
                @Override
                public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                    String responseBody = response.body().get("UploadJsonResult").toString();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body().get("UploadJsonResult").toString();
                            if (data.equals("")) {
                            } else {
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                                    if (endIndex < stock.getProductList().size()) {
                                        int startIndex1 = endIndex;
                                        int endIndex1 = 0;
                                        if (startIndex1 + 200 < stock.getProductList().size()) {
                                            endIndex1 = startIndex1 + 200;
                                        } else {
                                            endIndex1 = stock.getProductList().size();
                                        }
                                        UploadStockRecursive(status, startIndex1, endIndex1, stock);
                                    } else {
                                        db.open();
                                        db.updateStockTransactionDataStatus(stock.getTransactionId());
                                        dialog.cancel();
                                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                                        TesterStockActivity.this.finish();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            db.open();
                            dialog.cancel();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - " + e.toString() + " - Please Try Again");
                        }
                    } else {
                        dialog.cancel();
                        AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER + " - Please Try Again");
                    }
                }

                @Override
                public void onFailure(Call<JsonObject> call, Throwable t) {
                    dialog.cancel();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INTERNET_NOT_AVALABLE + " - Please Try Again");
                }
            });


        } catch (JSONException e) {
            e.fillInStackTrace();
            dialog.cancel();
            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON + " - Please Try Again");
        }
    }

    class InsertAsync extends AsyncTask<Boolean, Void, Void> {
        boolean flag = false;

        @Override
        protected void onPreExecute() {
            super.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();
        }

        @Override
        protected Void doInBackground(Boolean... bool) {
            flag = bool[0];
            db.open();
            db.insertTesterCapturedData(visit_date, listDataChild, listDataHeader, bool[0], counter_id);
            uploadData(bool[0]);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.cancel();
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.filter_menu_stock, 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();
        } else if (id == R.id.filled_history) {
            startActivity(new Intent(context, FilledRegularStockDataActivity.class).putExtra(CommonString.KEY_ACTIVITY, "Tester"));
            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
        }

        return super.onOptionsItemSelected(item);
    }

    private boolean validate_regular_stock() {
        check_flag = true;
        if (listDataHeader.size() > 0) {
            for (int k = 0; k < listDataHeader.size(); k++) {
                List<ProductMaster> child_list = listDataChild.get(listDataHeader.get(k));
                for (int i = 0; i < child_list.size(); i++) {
                    if (child_list.get(i).isSelected() && child_list.get(i).getStock_receive() != child_list.get(i).getStock()) {
                        if (child_list.get(i).getReasonId() == 0) {
                            check_flag = false;
                            AlertandMessages.showToastMsg(context, "Please Select Reason");
                            break;
                        }
                    }

                }
                if (!check_flag) {
                    break;
                }
            }
        }

        return check_flag;

    }

}
