package cpm.com.gskmtorange.gsk_dailyentry;

import android.annotation.SuppressLint;
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.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.Spanned;
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.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.interfaces.DialogCallbackListener;
import cpm.com.gskmtorange.xmlGetterSetter.MAPPING_PLANOGRAM_DataGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.StockFacing_PlanogramTrackerDataGetterSetter;

public class MSL_Availability_StockFacingActivity extends AppCompatActivity implements DialogCallbackListener {
    ExpandableListView expandableListView;
    private Context context;
    TextView txt_mslAvailabilityName;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> headerDataList;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> childDataList;
    List<MSL_AvailabilityStockFacingGetterSetter> hashMapListHeaderData;
    HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> hashMapListChildData;
    List<Integer> checkHeaderArray = new ArrayList<>();
    boolean checkflag = true;
    ExpandableListAdapter adapter;
    ImageView camera1, camera2, camera3, camera4;
    LinearLayout lin_camera1, lin_camera2, lin_camera3, lin_camera4;
    GSKOrangeDB db;
    String categoryName, categoryId, storeId, Error_Message = "";
    String store_id, store_flag_hide, visit_date, username, intime, date, keyAccount_id, class_id, storeType_id, camera_allow, country_id, store_flag_str;
    boolean isDialogOpen = true;
    private SharedPreferences preferences;
    int scrollPosition = 0;

    String str_planogram = "", _pathforcheck = "";

    ArrayList<StockFacing_PlanogramTrackerDataGetterSetter> planogramShelfHeaderDataList = new ArrayList<>();
    ArrayList<StockFacing_PlanogramTrackerDataGetterSetter> planogramSkuChildDataList;
    HashMap<StockFacing_PlanogramTrackerDataGetterSetter, ArrayList<StockFacing_PlanogramTrackerDataGetterSetter>> planogramHashMapListChildData = new HashMap<>();
    boolean editFlag = false;
    public static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/";
    LinearLayout pricingLL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_msl__availability_stock_facing);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
            txt_mslAvailabilityName = (TextView) findViewById(R.id.txt_mslAvailabilityName);
            camera1 = (ImageView) findViewById(R.id.img_camera1);
            camera2 = (ImageView) findViewById(R.id.img_camera2);
            camera3 = (ImageView) findViewById(R.id.img_camera3);
            camera4 = (ImageView) findViewById(R.id.img_camera4);
            lin_camera1 = (LinearLayout) findViewById(R.id.lin_camera1);
            lin_camera2 = (LinearLayout) findViewById(R.id.lin_camera2);
            lin_camera3 = (LinearLayout) findViewById(R.id.lin_camera3);
            lin_camera4 = (LinearLayout) findViewById(R.id.lin_camera4);
            pricingLL = findViewById(R.id.pricingLL);
            context = this;
            db = new GSKOrangeDB(this);
            db.open();
            //preference data
            preferences = PreferenceManager.getDefaultSharedPreferences(this);
            CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
            store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
            store_flag_hide = preferences.getString(CommonString.KEY_STORE_FLAG_FACING_HIDE, null);
            visit_date = preferences.getString(CommonString.KEY_DATE, null);
            date = preferences.getString(CommonString.KEY_DATE, null);
            username = preferences.getString(CommonString.KEY_USERNAME, null);
            intime = preferences.getString(CommonString.KEY_STORE_IN_TIME, "");
            keyAccount_id = preferences.getString(CommonString.KEY_KEYACCOUNT_ID, "");
            class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
            storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");
            camera_allow = preferences.getString(CommonString.KEY_CAMERA_ALLOW, "");
            country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
            store_flag_str = preferences.getString(CommonString.KEY_STORE_FLAG, null);
            //Intent data
            categoryName = getIntent().getStringExtra("categoryName");
            categoryId = getIntent().getStringExtra("categoryId");
            if (country_id != null && country_id.equals("5")) {
                pricingLL.setVisibility(View.GONE);
            } else {
                pricingLL.setVisibility(View.VISIBLE);
            }
            toolbar.setTitle(getResources().getString(R.string.title_activity_msl__availability));
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            str_planogram = CommonString.getDownloadedImageFolder(context);
            prepareList();
            prepareDefaultList();
            cameraMethod();
            final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(view -> {
                expandableListView.clearFocus();
                adapter.notifyDataSetChanged();
                if (validateData(hashMapListHeaderData, hashMapListChildData)) {
                    db.open();
                    if (db.checkMsl_Availability_StockFacingDataNew(store_id, categoryId, visit_date)) {
                        db.updateMSL_Availability_StockFacingNew(visit_date, store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                        Snackbar.make(expandableListView, getResources().getString(R.string.update_message), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                        /*ArrayList<MSL_AvailabilityStockFacingGetterSetter> msl_availabilityStockFacingList;
                        String mslAvailability_stockFacing_xml = "";
                        String onXML = "";
                        db.open();
                        Log.d("listdata", store_id + "," + visit_date);
                        msl_availabilityStockFacingList = db.getMSL_Availability_StockFacing_UploadServerDataNew(store_id, visit_date,
                                null, null, null,CommonString.TABLE_MAPPING_STOCK_STOREWISE);
                        Log.d("msllistsize", String.valueOf(msl_availabilityStockFacingList.size()));

                        if (msl_availabilityStockFacingList.size() > 0) {
                            for (int j = 0; j < msl_availabilityStockFacingList.size(); j++) {
                                if (!msl_availabilityStockFacingList.get(j).getSku_id().equals("0")) {

                                    String stock, pricing;
                                    if (!msl_availabilityStockFacingList.get(j).getStock().equals("")) {
                                        stock = msl_availabilityStockFacingList.get(j).getStock();
                                    } else {
                                        stock = "0";
                                    }
                                    if (!msl_availabilityStockFacingList.get(j).getPricingStock().equals("")) {
                                        pricing = msl_availabilityStockFacingList.get(j).getPricingStock();
                                    } else {
                                        pricing = "-1";
                                    }
                                    onXML = "[ST]"
                                            + "[MID]" + "0" + "[/MID]"
                                            //+ "[USERID]" + userId + "[/USERID]"
                                            + "[SID]" + Integer.parseInt(msl_availabilityStockFacingList.get(j).getSku_id()) + "[/SID]"
                                            + "[MBQ]" + Integer.parseInt(msl_availabilityStockFacingList.get(j).getMbq()) + "[/MBQ]"
                                            + "[AVL]" + Integer.parseInt(msl_availabilityStockFacingList.get(j).getToggleValue()) + "[/AVL]"
                                            + "[FC]" + Double.parseDouble(msl_availabilityStockFacingList.get(j).getFacing()) + "[/FC]"
                                            + "[SK]" + Integer.parseInt(stock) + "[/SK]"
                                            + "[PRICING]" + Double.parseDouble(pricing) + "[/PRICING]"
                                            + "[ML]" + Integer.parseInt(msl_availabilityStockFacingList.get(j).getMust_have()) + "[/ML]" +
                                            "[/ST]";

                                    mslAvailability_stockFacing_xml = mslAvailability_stockFacing_xml + onXML;
                                }
                            }
                            final String sos_xml = "[DATA]" + mslAvailability_stockFacing_xml + "[/DATA]";
                            Log.d("MSL_DATA", sos_xml);
                        }*/
                    } else {
                        db.InsertMSL_Availability_StockFacingNew(visit_date, store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                         Snackbar.make(expandableListView, getResources().getString(R.string.save_message), Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                    }
                    finish();
                    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                } else {
                    Snackbar.make(expandableListView, Error_Message, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                    for (int i = 0; i < adapter.getGroupCount(); i++)
                        expandableListView.expandGroup(i);
                }

            });

            expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                    expandableListView.invalidate();

                    int lastItem = firstVisibleItem + visibleItemCount;

                    if (firstVisibleItem == 0) {
                        fab.show();//.setVisibility(View.VISIBLE);
                    } else if (lastItem == totalItemCount) {
                        fab.hide();//setVisibility(View.INVISIBLE);
                    } else {
                        fab.show();//setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onScrollStateChanged(AbsListView arg0, int arg1) {
                    InputMethodManager inputManager = (InputMethodManager) context
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (getCurrentFocus() != null) {
                        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                        getCurrentFocus().clearFocus();
                    }
                    expandableListView.invalidateViews();
                }
            });

            // Listview Group click listener
            expandableListView.setOnGroupClickListener((parent, v, groupPosition, id) -> false);

            // Listview Group expanded listener
            expandableListView.setOnGroupExpandListener(groupPosition -> {
                InputMethodManager inputManager = (InputMethodManager) context
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            });

            // Listview Group collasped listener
            expandableListView.setOnGroupCollapseListener(groupPosition -> {
                InputMethodManager inputManager = (InputMethodManager) context
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            });

            // Listview on child click listener
            expandableListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> false);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (editFlag) {
                CommonFunctions.showAlertDialog(context, getResources().getString(R.string.data_will_be_lost));
            } else {
                finish();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            }
        } else if (id == R.id.action_planogram) {//Planogram Dialog
            expandableListView.clearFocus();
            final Dialog dialog = new Dialog(MSL_Availability_StockFacingActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.planogram_dialog_layout);
            dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            dialog.setCancelable(false);
            ArrayList<MAPPING_PLANOGRAM_DataGetterSetter> mappingPlanogramList;
            //Header
            if (country_id.equals("7") || country_id.equals("5") || country_id.equals("8")) {
                mappingPlanogramList = db.getMappingPlanogramData(categoryId, null, null, store_id, CommonString.TABLE_MAPPING_PLANOGRAM_STORE_WISE);
            } else if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
                mappingPlanogramList = db.getMappingPlanogramData(categoryId, storeType_id, class_id, null, CommonString.TABLE_MAPPING_PLANOGRAM_ADHOC);
            } else {
                mappingPlanogramList = db.getMappingPlanogramData(categoryId, storeType_id, class_id, null, CommonString.TABLE_MAPPING_PLANOGRAM);
            }

            //ImageView img_planogram = (ImageView) dialog.findViewById(R.id.img_planogram);
            WebView webView = (WebView) dialog.findViewById(R.id.webview);
            webView.setWebViewClient(new MyWebViewClient());
            webView.getSettings().setAllowFileAccess(true);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setBuiltInZoomControls(true);
            String planogram_image = "";
            if (mappingPlanogramList.size() > 0) {
                planogram_image = mappingPlanogramList.get(0).getPLANOGRAM_IMAGE();
            }
            if (!planogram_image.equals("")) {
                if (new File(str_planogram + planogram_image).exists()) {
                    Bitmap bmp = BitmapFactory.decodeFile(str_planogram + planogram_image);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    String imagePath = "file://" + str_planogram + "/" + planogram_image;
                    String html = "<html><head></head><body><img src=\"" + imagePath + "\"></body></html>";
                    webView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
                    dialog.show();
                }
            }


            ImageView cancel = (ImageView) dialog.findViewById(R.id.img_cancel);
            cancel.setOnClickListener(v -> {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                dialog.dismiss();
            });
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSelect(boolean flag) {
        if (flag) {
            if (!validateData(hashMapListHeaderData, hashMapListChildData)) {
                if (!camera_allow.equals("1")) {
                    db.deletePlanogramListStoreAndCategorywise(store_id, categoryId,
                            planogramShelfHeaderDataList, planogramHashMapListChildData);
                }
            }
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    @Override
    public void onSave(boolean flag) {

    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.clearCache(true);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
    }

    private void cameraMethod() {
        if (!camera_allow.equals("1")) {
            findViewById(R.id.lin_camera).setVisibility(View.GONE);
        } else {
            findViewById(R.id.lin_camera).setVisibility(View.GONE);
        }
    }

    //Planogram List for check and delete on backPress
    private void prepareDefaultList() {
        // Planogram After save shelf header data
        planogramShelfHeaderDataList = db.getPlanogramAddShelfHeaderAfterSaveData(store_id, categoryId);
        if (planogramShelfHeaderDataList.size() > 0) {
            for (int i = 0; i < planogramShelfHeaderDataList.size(); i++) {
                planogramSkuChildDataList = db.getStockAndFacingPlanogramAfterSKUData(planogramShelfHeaderDataList.get(i).getKey_id());
                //After save sku child data
                if (planogramSkuChildDataList.size() > 0) {
                    planogramHashMapListChildData.put(planogramShelfHeaderDataList.get(i), planogramSkuChildDataList);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
    }

    private void prepareList() {
        try {
            hashMapListHeaderData = new ArrayList<>();
            hashMapListChildData = new HashMap<>();
            //Header
            if (country_id.equals("7") || country_id.equals("8") || country_id.equals("17")) {
                headerDataList = db.getMSL_Availability_StockFacingHeaderData(categoryId, null, null, null,
                        store_id, CommonString.TABLE_MAPPING_STOCK_STOREWISE, CommonString.TABLE_MAPPING_SOS_TARGET, store_flag_hide);
            } else if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
                headerDataList = db.getMSL_Availability_StockFacingHeaderData(categoryId, keyAccount_id, storeType_id, class_id, store_id,
                        CommonString.TABLE_MAPPING_STOCK_ADHOC, CommonString.TABLE_MAPPING_SOS_TARGET_ADHOC, store_flag_hide);
            } else {
                headerDataList = db.getMSL_Availability_StockFacingHeaderData(categoryId, keyAccount_id, storeType_id, class_id,
                        store_id, CommonString.TABLE_MAPPING_STOCK, CommonString.TABLE_MAPPING_SOS_TARGET, store_flag_hide);
            }
            if (headerDataList.size() > 0) {
                for (int i = 0; i < headerDataList.size(); i++) {
                    hashMapListHeaderData.add(headerDataList.get(i));
                    if (country_id.equals("7") || country_id.equals("8") || country_id.equals("17")) {
                        db.open();
                        childDataList = db.getMSL_Availability_StockFacingSKUDataNewUpdate(headerDataList.get(i).getSub_category_id(),
                                categoryId, headerDataList.get(i).getBrand_id(), null, null, null, store_id,
                                CommonString.TABLE_MAPPING_STOCK_STOREWISE, store_flag_hide, visit_date, false);
                        updateCoverage(CommonString.TABLE_MAPPING_STOCK_STOREWISE);
                    } else if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
                        childDataList = db.getMSL_Availability_StockFacingSKUDataNewUpdate(headerDataList.get(i).getSub_category_id(),
                                categoryId, headerDataList.get(i).getBrand_id(), keyAccount_id, storeType_id, class_id, store_id,
                                CommonString.TABLE_MAPPING_STOCK_ADHOC, store_flag_hide, visit_date, false);
                        updateCoverage(CommonString.TABLE_MAPPING_STOCK_ADHOC);
                    } else {
                        childDataList = db.getMSL_Availability_StockFacingSKUDataNewUpdate(headerDataList.get(i).getSub_category_id(), categoryId,
                                headerDataList.get(i).getBrand_id(), keyAccount_id, storeType_id, class_id, store_id,
                                CommonString.TABLE_MAPPING_STOCK, store_flag_hide, visit_date, false);
                        updateCoverage(CommonString.TABLE_MAPPING_STOCK);
                    }
                    hashMapListChildData.put(hashMapListHeaderData.get(i), childDataList);
                }
            }

            adapter = new ExpandableListAdapter(this, hashMapListHeaderData, hashMapListChildData);
            expandableListView.setAdapter(adapter);
            //expand all
            for (int i = 0; i < adapter.getGroupCount(); i++)
                expandableListView.expandGroup(i);

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

    boolean validateData(List<MSL_AvailabilityStockFacingGetterSetter> listDataHeader,
                         HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> listDataChild) {
        boolean flag = true, child_flag = true, all_flag = true;
        checkHeaderArray.clear();
        int childCount = 0;
        //temp list data for empty only
        List<MSL_AvailabilityStockFacingGetterSetter> listDataHeaderTemp = new ArrayList<>();
        HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> listDataChildTemp = new HashMap<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            flag = true;
            List<MSL_AvailabilityStockFacingGetterSetter> listTemp = new ArrayList<>();
            for (int j = 0; j < listDataChild.get(listDataHeader.get(i)).size(); j++) {
                child_flag = true;
                MSL_AvailabilityStockFacingGetterSetter data = listDataChild.get(listDataHeader.get(i)).get(j);
                String stock = data.getStock();
                String faceup = data.getFacing();
                String defaultpricing = data.getPricing();
                String pricing = data.getPricingStock();
                String companyId = data.getCompany_id();
                String must_have = data.getMust_have();
                //Company_id
                if (companyId.equals("1")) {
                    if (must_have.equals("1")) {
                        //usk ksa pricing
                        if (!defaultpricing.equals("0")) {
                            if (!country_id.equals("17") && pricing.equals("")) {
                                if (!checkHeaderArray.contains(i)) {
                                    checkHeaderArray.add(i);
                                }
                                scrollPosition = i + j + childCount;
                                all_flag = false;
                                flag = false;
                                child_flag = false;
                                Error_Message = getResources().getString(R.string.title_activity_stock_pricing);
                            }
                        }

                        if (store_flag_hide.equals("0") && !country_id.equals("15")) {
                            if (!country_id.equals("17") && faceup.equals("")) {
                                if (!checkHeaderArray.contains(i)) {
                                    checkHeaderArray.add(i);
                                }
                                scrollPosition = i + j + childCount;
                                all_flag = false;
                                flag = false;
                                child_flag = false;
                                Error_Message = getResources().getString(R.string.faceup_value);
                            } else {
                                if (data.getToggleValue().equals("0") && !country_id.equals("10")) {
                                    if (stock.equals("")) {
                                        if (!checkHeaderArray.contains(i)) {
                                            checkHeaderArray.add(i);
                                        }
                                        scrollPosition = i + j + childCount;
                                        all_flag = false;
                                        flag = false;
                                        child_flag = false;
                                        Error_Message = getResources().getString(R.string.stock_value);
                                    }
                                } else {
                                    //for Egypt
                                    if (country_id.equals("6")) {
                                        if (stock.equals("")) {
                                            if (!checkHeaderArray.contains(i)) {
                                                checkHeaderArray.add(i);
                                            }
                                            scrollPosition = i + j + childCount;
                                            all_flag = false;
                                            flag = false;
                                            child_flag = false;
                                            Error_Message = getResources().getString(R.string.stock_value);
                                        }
                                    }
                                }
                            }
                        } else {
                            if (data.getToggleValue().equals("0") && !country_id.equals("10")) {
                                if (stock.equals("")) {
                                    if (!checkHeaderArray.contains(i)) {
                                        checkHeaderArray.add(i);
                                    }
                                    scrollPosition = i + j + childCount;
                                    all_flag = false;
                                    flag = false;
                                    child_flag = false;
                                    Error_Message = getResources().getString(R.string.stock_value);
                                }
                            } else {
                                //for Egypt
                                if (country_id.equals("6")) {
                                    if (stock.equals("")) {
                                        if (!checkHeaderArray.contains(i)) {
                                            checkHeaderArray.add(i);
                                        }
                                        all_flag = false;
                                        flag = false;
                                        child_flag = false;
                                        Error_Message = getResources().getString(R.string.stock_value);
                                    }
                                }
                            }
                        }

                    }
                } else {
                    if (store_flag_hide.equals("0")) {
                        if (country_id != null && !country_id.equals("17") && faceup.equals("")) {
                            if (!checkHeaderArray.contains(i)) {
                                checkHeaderArray.add(i);
                            }
                            scrollPosition = i + j + childCount;
                            all_flag = false;
                            flag = false;
                            child_flag = false;
                            Error_Message = getResources().getString(R.string.faceup_value);
                        }
                    }
                }
                if (!child_flag)
                    listTemp.add(data);
            }

            if (!flag) {
                listDataHeaderTemp.add(listDataHeader.get(i));
                listDataChildTemp.put(listDataHeader.get(i), listTemp);
            } else {
                childCount = childCount + listDataChild.get(listDataHeader.get(i)).size();
            }
        }

        if (!all_flag) {
            adapter = new ExpandableListAdapter(context, listDataHeaderTemp, listDataChildTemp);
            expandableListView.setAdapter(adapter);
            checkflag = false;
        } else {
            checkflag = true;
        }

        return all_flag;
    }


    @Override
    public void onBackPressed() {
        if (editFlag) {
            CommonFunctions.showAlertDialog(context, getResources().getString(R.string.data_will_be_lost));
        } else {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

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

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

        @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) {
            MSL_AvailabilityStockFacingGetterSetter headerTitle = (MSL_AvailabilityStockFacingGetterSetter) getGroup(groupPosition);

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_msl_availability_stock_facing_header, null, false);
            }

            TextView txt_categoryHeader = (TextView) convertView.findViewById(R.id.txt_categoryHeader);
            RelativeLayout rel_header = (RelativeLayout) convertView.findViewById(R.id.rel_categoryHeader);
            ImageView img_camera = (ImageView) convertView.findViewById(R.id.img_camera);
            CardView card_view = (CardView) convertView.findViewById(R.id.card_view);
            txt_categoryHeader.setTypeface(null, Typeface.BOLD);

            if (headerTitle.getCompany_id().equals("1")) {
                txt_categoryHeader.setTextColor(getResources().getColor(R.color.header_text_color));
            } else {
                txt_categoryHeader.setTextColor(getResources().getColor(R.color.black));
            }
            txt_categoryHeader.setText(headerTitle.getSub_category() + "-" + headerTitle.getBrand());

            if (!checkflag) {
                if (checkHeaderArray.contains(groupPosition)) {
                    card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                    txt_categoryHeader.setTextColor(getResources().getColor(R.color.white));
                } else {
                    card_view.setCardBackgroundColor(getResources().getColor(R.color.grey_background));
                }
            }

            return convertView;
        }

        @Override
        public Object getChild(int groupPosition, int childPosititon) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
        }

        @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 MSL_AvailabilityStockFacingGetterSetter childData =
                    (MSL_AvailabilityStockFacingGetterSetter) 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_msl_availability_stock_facing_child, null, false);

                holder = new ViewHolder();
                holder.cardView = (CardView) convertView.findViewById(R.id.card_view);
                holder.lin_category = (LinearLayout) convertView.findViewById(R.id.lin_category);
                holder.txt_skuName = (TextView) convertView.findViewById(R.id.txt_skuName);
                holder.txt_mbq = (TextView) convertView.findViewById(R.id.txt_mbq);
                holder.toggle_available = (ToggleButton) convertView.findViewById(R.id.toggle_available);
                holder.facing = (EditText) convertView.findViewById(R.id.ed_facing);
                holder.facing.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
                holder.stock = (EditText) convertView.findViewById(R.id.ed_stock);
                holder.ed_pricing = (EditText) convertView.findViewById(R.id.ed_pricing);
                holder.facing_view = convertView.findViewById(R.id.facing_view);
                holder.stock_view = convertView.findViewById(R.id.stock_view);
                holder.pricing_view = convertView.findViewById(R.id.pricing_view);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            // uae facing hide
            if (store_flag_hide.equals("1") || country_id.equals("15") || country_id.equals("17")) {
                holder.facing.setVisibility(View.GONE);
                holder.facing_view.setVisibility(View.GONE);
            } else {
                holder.facing.setVisibility(View.VISIBLE);
                holder.facing_view.setVisibility(View.VISIBLE);
            }
            holder.txt_skuName.setText(childData.getSku());
            holder.txt_mbq.setText(childData.getMbq());

            if (childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                holder.lin_category.setBackgroundColor(getResources().getColor(R.color.light_green_background));
                holder.txt_mbq.setVisibility(View.VISIBLE);
                holder.toggle_available.setVisibility(View.VISIBLE);
                holder.toggle_available.setId(childPosition);
                if (country_id.equals("6") || country_id.equals("10")) {
                    holder.stock.setVisibility(View.VISIBLE);
                    holder.stock_view.setVisibility(View.VISIBLE);
                }
                else {
                    if (childData.getToggleValue().equals("1")) {
                        holder.stock.setVisibility(View.GONE);
                        holder.stock_view.setVisibility(View.GONE);
                    } else {
                        holder.stock.setVisibility(View.VISIBLE);
                        holder.stock_view.setVisibility(View.VISIBLE);
                    }
                }
            } else {
                holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
                holder.txt_mbq.setVisibility(View.GONE);
                holder.toggle_available.setVisibility(View.GONE);
                holder.toggle_available.setId(childPosition);
                holder.stock.setVisibility(View.GONE);
                holder.stock_view.setVisibility(View.GONE);
            }

            if (country_id != null && !country_id.equals("17")) {
                if (childData.getPricing().equals("0")) {
                    holder.ed_pricing.setVisibility(View.GONE);
                    holder.pricing_view.setVisibility(View.GONE);
                    holder.ed_pricing.setId(childPosition);
                    holder.pricing_view.setId(childPosition);
                } else {
                    holder.ed_pricing.setVisibility(View.VISIBLE);
                    holder.pricing_view.setVisibility(View.VISIBLE);
                    holder.ed_pricing.setId(childPosition);
                    holder.pricing_view.setId(childPosition);
                }
            }

            if (childData.getCompany_id().equals("1")) {
                if (country_id != null && country_id.equals("17") && !childData.getPricing().equals("0")) {
                    holder.ed_pricing.setVisibility(View.VISIBLE);
                    holder.pricing_view.setVisibility(View.VISIBLE);
                    holder.ed_pricing.setId(childPosition);
                    holder.pricing_view.setId(childPosition);
                } else {
                    holder.ed_pricing.setVisibility(View.GONE);
                    holder.pricing_view.setVisibility(View.GONE);
                    holder.ed_pricing.setId(childPosition);
                    holder.pricing_view.setId(childPosition);
                }
                if (childData.getMust_have().equals("1")) {
                    holder.txt_skuName.setTextColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    if (country_id != null && country_id.equals("17")) {
                        holder.toggle_available.setVisibility(View.VISIBLE);
                        holder.toggle_available.setId(childPosition);
                    }
                    holder.txt_skuName.setTextColor(getResources().getColor(R.color.blue));
                }
            } else {
                if (country_id != null && country_id.equals("17")) {
                    holder.ed_pricing.setVisibility(View.GONE);
                    holder.pricing_view.setVisibility(View.GONE);
                    holder.ed_pricing.setId(childPosition);
                    holder.pricing_view.setId(childPosition);
                    holder.toggle_available.setVisibility(View.VISIBLE);
                    holder.toggle_available.setId(childPosition);
                }

                holder.txt_skuName.setTextColor(getResources().getColor(R.color.black));
            }

            final ViewHolder finalHolder = holder;
            holder.toggle_available.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (buttonView.isPressed()) {
                    editFlag = true;
                    if (isChecked) {
                        childData.setToggleValue("1");
                        //for Egypt
                        finalHolder.stock.setVisibility(country_id != null && (country_id.equals("6")||country_id.equals("10")) ? View.VISIBLE : View.GONE);
                    } else {
                        childData.setToggleValue("0");
                        finalHolder.stock.setVisibility(country_id != null && country_id.equals("17") ? View.GONE : View.VISIBLE);
                        //If MBQ Value is 0
                        if (Integer.parseInt(childData.getMbq()) == 0) {
                            childData.setStock("0");
                            childData.setFacing("0");
                        } else {
                            //for Egypt
                            if (country_id.equals("6")|| country_id.equals("10")) {
                                childData.setStock("");
                                childData.setFacing("");
                            }
                        }
                    }
                    expandableListView.clearFocus();
                    expandableListView.invalidateViews();
                }
            });

            if (childData.getToggleValue().equals("1")) {
                holder.toggle_available.setChecked(true);
                if ((country_id.equals("6")|| (country_id.equals("10"))) && childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                    finalHolder.stock.setVisibility(View.VISIBLE);
                } else {
                    finalHolder.stock.setVisibility(View.GONE);
                    childData.setStock("");
                }
            } else {
                holder.toggle_available.setChecked(false);
                finalHolder.stock.setVisibility((country_id != null && country_id.equals("17") && (!childData.getCompany_id().equals("1") || childData.getCompany_id().equals("1") && childData.getMust_have().equals("0"))) ? View.GONE : View.VISIBLE);
            }

            holder.stock.setOnFocusChangeListener((v, hasFocus) -> {
                final EditText caption = (EditText) v;
                String edStock = caption.getText().toString().replaceFirst("^0+(?!$)", "");
                editFlag = true;
                if (!edStock.equals("")) {
                    String stock = edStock;
                    //for Egypt
                    if ((country_id.equals("6")||country_id.equals("10")) && childData.getToggleValue().equals("1")) {
                        if (!childData.getFacing().equals("")) {
                            if (Integer.parseInt(stock) >= 0 && Double.parseDouble(childData.getFacing()) <= Integer.parseInt(stock)) {
                                childData.setStock(stock);
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                builder.setMessage(getString(R.string.check_faceup))
                                        .setCancelable(false)
                                        .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                            finalHolder.stock.setText("");
                                            dialog.dismiss();
                                        });
                                AlertDialog alert = builder.create();
                                alert.show();
                            }
                        } else {
                            childData.setStock(stock);
                        }
                    } else {
                        int mbq = Integer.parseInt(childData.getMbq());
                        if (mbq != 0) {
                            if (Integer.parseInt(stock) >= 0 && Integer.parseInt(stock) < mbq) {
                                if (!childData.getFacing().equals("")) {
                                    if (Integer.parseInt(stock) >= 0 && Double.parseDouble(childData.getFacing()) <= Integer.parseInt(stock)) {
                                        childData.setStock(stock);
                                    } else {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                        builder.setMessage(getString(R.string.check_faceup))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                    finalHolder.stock.setText("");
                                                    dialog.dismiss();
                                                });
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    }
                                } else {
                                    childData.setStock(stock);
                                }
                            } else {
                                if (isDialogOpen) {
                                    isDialogOpen = !isDialogOpen;
                                    AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                    builder.setMessage(getString(R.string.check_stock))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                finalHolder.stock.setText("");
                                                dialog.dismiss();
                                                isDialogOpen = !isDialogOpen;
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            }
                        } else {
                            if (Integer.parseInt(stock) > 0) {
                                if (isDialogOpen) {
                                    isDialogOpen = !isDialogOpen;
                                    AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                    builder.setMessage(getString(R.string.check_stock))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                finalHolder.stock.setText("");
                                                dialog.dismiss();
                                                isDialogOpen = !isDialogOpen;
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            }
                        }
                    }
                } else {
                    childData.setStock("");
                }
            });
            holder.stock.setText(childData.getStock());

            holder.ed_pricing.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    final EditText Caption = (EditText) v;
                    String value1 = Caption.getText().toString().replaceFirst("^0+(?!$)", "");
                    if (value1.equals("")) {
                        childData.setPricingStock("");
                        finalHolder.ed_pricing.setText("");
                        finalHolder.ed_pricing.setId(childPosition);
                    } else {
                        childData.setPricingStock(value1);
                        finalHolder.ed_pricing.setText(value1);
                        finalHolder.ed_pricing.setId(childPosition);
                    }
                }
            });

            holder.ed_pricing.setText(childData.getPricingStock());

            final ViewHolder finalHolder1 = holder;
            final ViewHolder finalHolder2 = holder;
            holder.facing.setOnFocusChangeListener((v, hasFocus) -> {
                final EditText caption = (EditText) v;
                String edFaceup = caption.getText().toString().replaceFirst("^0+(?!$)", "");
                editFlag = true;
                if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                    double faceup = Double.parseDouble(edFaceup);
                    int num = (int) faceup;
                    int faceint = (int) ((faceup % 1.0) * 10);
                    if (faceint != 0) {
                        if ((faceup % 1.0) * 10 != 5) {
                            faceint = 5;
                            edFaceup = String.valueOf(num + faceint / 10.0);
                            finalHolder2.facing.setText(edFaceup);
                        }
                    }
                }

                boolean isFill = false;
                //Toggle is no selected
                if (childData.getToggleValue().equals("0")) {
                    if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                        int mbq = Integer.parseInt(childData.getMbq());
                        if (mbq != 0) {
                            if (Double.parseDouble(edFaceup) >= 0 && Double.parseDouble(edFaceup) < mbq) {
                                if (!childData.getStock().equals("")) {
                                    String faceup = edFaceup.replaceFirst("^0+(?!$)", "");
                                    if (Double.parseDouble(faceup) <= Integer.parseInt(childData.getStock())) {
                                        isFill = true;
                                    } else {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                        builder.setMessage(getString(R.string.check_faceup))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                    finalHolder1.facing.setText("");
                                                    dialog.dismiss();
                                                    finalHolder2.facing.setText("");
                                                });
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    }
                                } else {
                                    isFill = true;
                                }
                            } else {
                                if (isDialogOpen) {
                                    isDialogOpen = !isDialogOpen;
                                    AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                    builder.setMessage(getString(R.string.check_faceing))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                finalHolder.facing.setText("");
                                                dialog.dismiss();
                                                isDialogOpen = !isDialogOpen;
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            }
                        } else {
                            if (Double.parseDouble(edFaceup) > 0) {
                                if (isDialogOpen) {
                                    isDialogOpen = !isDialogOpen;
                                    AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                    builder.setMessage(getString(R.string.check_faceing))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                finalHolder.facing.setText("");
                                                dialog.dismiss();
                                                isDialogOpen = !isDialogOpen;
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            }
                        }

                    }
                } else {
                    if (country_id.equals("6")|| country_id.equals("10")) {
                        if (!childData.getStock().equals("")) {
                            String faceup = edFaceup.replaceFirst("^0+(?!$)", "");
                            if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                                if (Double.parseDouble(faceup) <= Integer.parseInt(childData.getStock())) {
                                    isFill = true;
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(_context);
                                    builder.setMessage(getString(R.string.check_faceup))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                                                finalHolder1.facing.setText("");
                                                dialog.dismiss();
                                                finalHolder2.facing.setText("");
                                            });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            } else {
                                isFill = true;
                            }
                        } else {
                            isFill = true;
                        }
                    } else {
                        isFill = true;
                    }
                }

                if (isFill) {
                    if (!edFaceup.equals("") && !edFaceup.equals(".")) {
                        String faceup = "";
                        if (edFaceup.equals("0") || edFaceup.equals(".0")) {
                            faceup = "0";
                        } else {
                            faceup = edFaceup.replaceFirst("^0+(?!$)", "");
                        }
                        childData.setFacing(faceup);
                    } else {
                        childData.setFacing("");
                    }
                }
            });

            holder.facing.setText(childData.getFacing());
            //empty check color change
            if (!checkflag) {
                boolean tempflag = false;
                //usk pricing
                if (!childData.getPricing().equals("0")) {
                    if (holder.ed_pricing.getText().toString().equals("")) {
                        holder.ed_pricing.setBackgroundColor(getResources().getColor(R.color.white));
                        holder.ed_pricing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.ed_pricing.setHint(getString(R.string.empty));
                        tempflag = true;
                    }
                }

                if (childData.getCompany_id().equals("1")) {
                    if (childData.getToggleValue().equals("0")) {
                        if (holder.stock.getText().toString().equals("")) {
                            holder.stock.setBackgroundColor(getResources().getColor(R.color.white));
                            holder.stock.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                            holder.stock.setHint(getString(R.string.empty));
                            tempflag = true;
                        }

                        if (holder.facing.getText().toString().equals("")) {
                            holder.facing.setBackgroundColor(getResources().getColor(R.color.white));
                            holder.facing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                            holder.facing.setHint(getString(R.string.empty));
                            tempflag = true;
                        }
                    } else {
                        if (childData.getMust_have().equals("1")) {
                            if (holder.facing.getText().toString().equals("")) {
                                holder.facing.setBackgroundColor(getResources().getColor(R.color.white));
                                holder.facing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                                holder.facing.setHint(getString(R.string.empty));
                                tempflag = true;
                            }
                            //for Egypt
                            if (country_id.equals("6")) {
                                if (holder.stock.getText().toString().equals("")) {
                                    holder.stock.setBackgroundColor(getResources().getColor(R.color.white));
                                    holder.stock.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                                    holder.stock.setHint(getString(R.string.empty));
                                    tempflag = true;
                                }
                            }
                        } else {
                            holder.facing.setHint("");
                        }
                    }


                    if (tempflag) {
                        holder.lin_category.setBackgroundResource(R.drawable.cardview_error_border);
                    } else {
                        if (childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.light_green_background));
                        } else {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
                        }
                    }
                } else {
                    if (holder.facing.getText().toString().equals("")) {
                        holder.facing.setBackgroundColor(getResources().getColor(R.color.white));
                        holder.facing.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.facing.setHint(getString(R.string.empty));
                        tempflag = true;
                    }

                    if (tempflag) {
                        holder.lin_category.setBackgroundResource(R.drawable.cardview_error_border);
                    } else {
                        if (childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.light_green_background));
                        } else {
                            holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
                        }
                    }
                }
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    public class ViewHolder {
        CardView cardView;
        TextView txt_skuName, txt_mbq;
        ToggleButton toggle_available;
        LinearLayout lin_category;
        EditText facing, stock, ed_pricing;
        View stock_view, pricing_view, facing_view;
    }


    @SuppressLint("LongLogTag")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("MSL_AVailability_StockFacing", "resultCode: " + resultCode);

        switch (requestCode) {
            case 100:
                //Planogram List for check and delete on backPress
                prepareDefaultList();
                if (db.isPlanogramAddShelfSaveData(store_id, categoryId)) {
                    camera1.setBackgroundResource(R.mipmap.new_no_camera_done_edit);
                } else {
                    camera1.setBackgroundResource(R.mipmap.new_no_camera);
                }

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

    public String PerfectDecimal(String str, int MAX_BEFORE_POINT, int MAX_DECIMAL) {
        if (str.charAt(0) == '.') str = "0" + str;
        int max = str.length();

        String rFinal = "";
        boolean after = false;
        int i = 0, up = 0, decimal = 0;
        char t;
        while (i < max) {
            t = str.charAt(i);
            if (t != '.' && after == false) {
                up++;
                if (up > MAX_BEFORE_POINT) return rFinal;
            } else if (t == '.') {
                after = true;
            } else {
                decimal++;
                if (decimal > MAX_DECIMAL)
                    return rFinal;
            }
            rFinal = rFinal + t;
            i++;
        }
        return rFinal;
    }

    public class DecimalDigitsInputFilter implements InputFilter {
        Pattern mPattern;

        public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
            mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher matcher = mPattern.matcher(dest);
            if (!matcher.matches())
                return "";
            return null;
        }
    }

    private void updateCoverage(String table) {
        long l = db.updateStockMapping(store_id, visit_date, table);
        if (l > 0) Log.e("CoverageUpdate", "" + l);
    }
}
