package cpm.com.gskmtorange.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 NewStockDataActivity extends AppCompatActivity implements DialogCallbackListener {
    private Context context;
    ExpandableListView expandableListView;
    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;

    //temp
   // public static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/";
    //ImageView bmImage;
    RelativeLayout view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_new_stock_data);

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

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

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

            //txt_mslAvailabilityName.setText(getResources().getString(R.string.title_activity_msl__availability));
            toolbar.setTitle(getResources().getString(R.string.title_activity_msl__availability));
            setSupportActionBar(toolbar);

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            str_planogram = CommonString.getDownloadedImageFolder(context);

            prepareList();

            //Camera
            prepareDefaultList();

            cameraMethod();

            final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {

                    expandableListView.clearFocus();
                    adapter.notifyDataSetChanged();

                    if (validateData(hashMapListHeaderData, hashMapListChildData)) {

                        db.open();

                        /*if (db.checkMsl_Availability_StockFacingData(store_id, categoryId)) {
                            db.updateMSL_Availability_StockFacing(store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                            Snackbar.make(view, getResources().getString(R.string.update_message), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        } else {
                            db.InsertMSL_Availability_StockFacing(store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                            Snackbar.make(view, getResources().getString(R.string.save_message), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }*/
                        if (db.checkMsl_Availability_StockFacingDataNew(store_id, categoryId, visit_date)) {
                            db.updateMSL_Availability_StockFacingNew(visit_date, store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                            Snackbar.make(view, getResources().getString(R.string.update_message), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        } else {
                            db.InsertMSL_Availability_StockFacingNew(visit_date, store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                            Snackbar.make(view, getResources().getString(R.string.save_message), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);

                        /*AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
                        builder.setMessage(getResources().getString(R.string.check_save_message))
                                .setCancelable(false)
                                .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        db.open();

                                        if (db.checkMsl_Availability_StockFacingData(store_id, categoryId)) {
                                            db.updateMSL_Availability_StockFacing(store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                                            Snackbar.make(view, getResources().getString(R.string.update_message), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                                        } else {
                                            db.InsertMSL_Availability_StockFacing(store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                                            Snackbar.make(view, getResources().getString(R.string.save_message), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                                        }
                                        finish();
                                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                                    }
                                })
                                .setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();*/
                    } else {
                        for (int i = 0; i < adapter.getGroupCount(); i++)
                            expandableListView.expandGroup(i);

                        /*AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
                        builder.setMessage(Error_Message)
                                .setCancelable(false)
                                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                       //expandableListView.smoothScrollToPosition(scrollPosition);

                                        dialog.dismiss();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();*/
                    }

                }
            });

            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(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                    return false;
                }
            });

            // Listview Group expanded listener
            expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                @Override
                public void onGroupExpand(int 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(new ExpandableListView.OnGroupCollapseListener() {
                @Override
                public void onGroupCollapse(int 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(new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                            int childPosition, long id) {
                    return 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(NewStockDataActivity.this, getResources().getString(R.string.data_will_be_lost));
            } else {
                finish();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            }


           /* AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
            builder.setTitle(getResources().getString(R.string.dialog_title));
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            //adapter.notifyDataSetChanged();

                            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);
                        }
                    })
                    .setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();*/
            //finish();
        } else if (id == R.id.action_planogram) {//Planogram Dialog
            expandableListView.clearFocus();

            //final Dialog dialog = new Dialog(Stock_FacingActivity.this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
            final Dialog dialog = new Dialog(NewStockDataActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            //dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            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")) {
                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 NewStockDataActivity.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);
                    // img_planogram.setRotation(90);
                    //img_planogram.setImageBitmap(bmp);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

                    String imagePath = "file://" + CommonString.getDownloadedImageFolder(context) + "/" + planogram_image;
                    String html = "<html><head></head><body><img src=\"" + imagePath + "\"></body></html>";
                    webView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");

                    dialog.show();
                } /*else {
                //webView.loadUrl(String.valueOf(R.drawable.sad_cloud));

                //img_planogram.setBackgroundResource(R.drawable.sad_cloud);
            }*/
            }


            ImageView cancel = (ImageView) dialog.findViewById(R.id.img_cancel);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    dialog.dismiss();
                }
            });

            //dialog.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSelect(boolean flag) {
        if (flag) {
            //adapter.notifyDataSetChanged();
            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() {
        /*cameraData = new Store_wise_camera_DataGetterSetter();

        if (db.isStorewiseCameraSave(store_id, categoryId)) {
            cameraData = db.getStore_wise_camera(store_id, categoryId);
        } else {
            cameraData.setStore_id(store_id);
            cameraData.setCategory_id(categoryId);
            cameraData.setCamera1("");
            cameraData.setCamera2("");
            cameraData.setCamera3("");
            cameraData.setCamera4("");
            cameraData.setCheckSaveStatus("0");
        }


        if (camera_allow.equals("1")) {

            findViewById(R.id.view_camera2).setVisibility(View.VISIBLE);
            findViewById(R.id.view_camera3).setVisibility(View.VISIBLE);

            if (cameraData.getCamera1().equals("")) {
                camera1.setBackgroundResource(R.mipmap.camera_orange);
            } else {
                camera1.setBackgroundResource(R.mipmap.camera_green);
            }

            if (cameraData.getCamera2().equals("")) {
                camera2.setBackgroundResource(R.mipmap.camera_orange);
            } else {
                camera2.setBackgroundResource(R.mipmap.camera_green);
            }

            if (cameraData.getCamera3().equals("")) {
                camera3.setBackgroundResource(R.mipmap.camera_orange);
            } else {
                camera3.setBackgroundResource(R.mipmap.camera_green);
            }

            if (cameraData.getCamera4().equals("")) {
                camera4.setBackgroundResource(R.mipmap.camera_orange);
            } else {
                camera4.setBackgroundResource(R.mipmap.camera_green);
            }


            lin_camera1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    _pathforcheck = "Stock_Camera1_" + store_id + "_" + categoryId
                            + "_" + visit_date.replace("/", "") + "_" + CommonFunctions.getCurrentTimeWithLanguage(getApplicationContext()).replace(":", "") + ".jpg";
                    path = str_planogram+ _pathforcheck;

                    startCameraActivity(3);
                }
            });

            lin_camera2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    _pathforcheck = "Stock_Camera2_" + store_id + "_" + categoryId
                            + "_" + visit_date.replace("/", "") + "_" + CommonFunctions.getCurrentTimeWithLanguage(getApplicationContext()).replace(":", "") + ".jpg";
                    path = str_planogram+ _pathforcheck;

                    startCameraActivity(4);
                }
            });

            lin_camera3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    _pathforcheck = "Stock_Camera3_" + store_id + "_" + categoryId
                            + "_" + visit_date.replace("/", "") + "_" + CommonFunctions.getCurrentTimeWithLanguage(getApplicationContext()).replace(":", "") + ".jpg";
                    path = str_planogram+ _pathforcheck;

                    startCameraActivity(5);
                }
            });

            lin_camera4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    _pathforcheck = "Stock_Camera4_" + store_id + "_" + categoryId
                            + "_" + visit_date.replace("/", "") + "_" + CommonFunctions.getCurrentTimeWithLanguage(getApplicationContext()).replace(":", "") + ".jpg";
                    path = str_planogram+ _pathforcheck;

                    startCameraActivity(6);
                }
            });

        } else {*/

        if (!camera_allow.equals("1")) {
            findViewById(R.id.lin_camera).setVisibility(View.GONE);
           /* findViewById(R.id.lin_camera).setVisibility(View.VISIBLE);

            findViewById(R.id.view_camera2).setVisibility(View.GONE);
            findViewById(R.id.view_camera3).setVisibility(View.GONE);

            lin_camera2.setVisibility(View.GONE);
            lin_camera3.setVisibility(View.GONE);
            lin_camera4.setVisibility(View.GONE);

            if (db.isPlanogramAddShelfSaveData(store_id, categoryId)) {
                camera1.setBackgroundResource(R.mipmap.new_no_camera_done_edit);
            } else {
                camera1.setBackgroundResource(R.mipmap.new_no_camera);
            }

            lin_camera1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(NewStockDataActivity.this,
                            StockFacing_PlanogramTrackerActivity.class);

                    intent.putExtra("storeId", store_id);
                    intent.putExtra("keyAccount_id", keyAccount_id);
                    intent.putExtra("class_id", class_id);
                    intent.putExtra("storeType_id", storeType_id);
                    intent.putExtra("categoryId", categoryId);
                    intent.putExtra("categoryName", categoryName);

                    startActivityForResult(intent, 100);
                }

            });*/
        } 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")) {
                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));
                    //childDataList = new ArrayList<>();
                    //childDataList = db.getMSL_Availability_StockFacingSKU_AfterSaveData(categoryId, headerDataList.get(i).getBrand_id(), store_id);
                    if (country_id.equals("7")) {
                        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);
                        // childDataList = db.getMSL_Availability_StockFacingSKUData(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);
                    } else if (store_flag_str.equalsIgnoreCase(CommonString.FROM_DEVIATION)) {
                        // childDataList = db.getMSL_Availability_StockFacingSKUData(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);
                        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_StockFacingSKUData(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);
                        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 NewStockDataActivity.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();

                //Company_id
                if (listDataChild.get(listDataHeader.get(i)).get(j).getCompany_id().equals("1")) {
                    if (data.getMust_have().equals("1")) {
                        /*if (!camera_allow.equalsIgnoreCase("1")) {
                            if (!(planogramShelfHeaderDataList.size() > 0)) {
                                flag = false;
                                Error_Message = getResources().getString(R.string.stock_planogram_data_noCamera_data);
                                break;
                            }
                        }*/

                        if (faceup.equals("")) {
                            if (!checkHeaderArray.contains(i)) {
                                checkHeaderArray.add(i);
                            }
                            //expandableListView.smoothScrollToPosition(i);
                            scrollPosition = i + j + childCount;

                            all_flag = false;
                            flag = false;
                            child_flag = false;
                            Error_Message = getResources().getString(R.string.faceup_value);
                            //break;
                        } else {
                            if (data.getToggleValue().equals("0")) {

                                if (stock.equals("")) {
                                    if (!checkHeaderArray.contains(i)) {
                                        checkHeaderArray.add(i);
                                    }
                                    //expandableListView.smoothScrollToPosition(i);
                                    scrollPosition = i + j + childCount;

                                    all_flag = false;
                                    flag = false;
                                    child_flag = false;
                                    Error_Message = getResources().getString(R.string.stock_value);
                                    //break;
                                }
                            } else {
                                //for Egypt
                                if (country_id.equals("6")) {
                                    if (stock.equals("")) {
                                        if (!checkHeaderArray.contains(i)) {
                                            checkHeaderArray.add(i);
                                        }
                                        //expandableListView.smoothScrollToPosition(i);
                                        scrollPosition = i + j + childCount;

                                        all_flag = false;
                                        flag = false;
                                        child_flag = false;
                                        Error_Message = getResources().getString(R.string.stock_value);
                                        // break;
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (faceup.equals("")) {
                        if (!checkHeaderArray.contains(i)) {
                            checkHeaderArray.add(i);
                        }
                        //expandableListView.smoothScrollToPosition(i);
                        scrollPosition = i + j + childCount;

                        all_flag = false;
                        flag = false;
                        child_flag = false;
                        Error_Message = getResources().getString(R.string.faceup_value);
                        // break;
                    }
                }
                if (!child_flag)
                    listTemp.add(data);

            }

            if (flag == false) {
                //checkflag = false;
                listDataHeaderTemp.add(listDataHeader.get(i));
                listDataChildTemp.put(listDataHeader.get(i), listTemp);

                //break;
            } else {
                childCount = childCount + listDataChild.get(listDataHeader.get(i)).size();
                //checkflag = true;
            }
        }

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

        return all_flag;
    }


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

        /*AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
        builder.setTitle(getResources().getString(R.string.dialog_title));
        builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        //adapter.notifyDataSetChanged();
                        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);
                    }
                })
                .setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();*/
        if (editFlag) {
            CommonFunctions.showAlertDialog(NewStockDataActivity.this, getResources().getString(R.string.data_will_be_lost));
        } else {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }


       /* if(flag){
            //adapter.notifyDataSetChanged();
            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);
        }*/


    }

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

            //empty check color change
            /*if (headerTitle.getCompany_id().equals("1")) {
                if (!checkflag) {
                    if (checkHeaderArray.contains(groupPosition)) {
                        //card_view.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        txt_categoryHeader.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        txt_categoryHeader.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                    }
                }
            } else {
                if (!checkflag) {
                    if (checkHeaderArray.contains(groupPosition)) {
                        txt_categoryHeader.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    } else {
                        txt_categoryHeader.setTextColor(getResources().getColor(R.color.black));
                    }
                }
            }*/

            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);
            NewStockDataActivity.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_data, null, false);

                holder = new NewStockDataActivity.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 NewStockDataActivity.DecimalDigitsInputFilter(3, 1)});
                holder.stock = (EditText) convertView.findViewById(R.id.ed_stock);
                holder.stock_view = convertView.findViewById(R.id.stock_view);
                convertView.setTag(holder);
            } else {
                holder = (NewStockDataActivity.ViewHolder) convertView.getTag();
            }

            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.facing.setVisibility(View.VISIBLE);


                if (country_id.equals("6")) {
                    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.facing.setVisibility(View.VISIBLE);
                holder.stock.setVisibility(View.GONE);
                holder.stock_view.setVisibility(View.GONE);
            }

            if (childData.getCompany_id().equals("1")) {

                if (childData.getMust_have().equals("1")) {
                    holder.txt_skuName.setTextColor(getResources().getColor(R.color.colorPrimary));
                } else {
                    holder.txt_skuName.setTextColor(getResources().getColor(R.color.blue));
                }

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


           /* if (childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")) {
                holder.lin_category.setBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else {
                holder.lin_category.setBackgroundColor(getResources().getColor(R.color.white));
                    *//*holder.txt_mbq.setVisibility(View.GONE);
                    holder.toggle_available.setVisibility(View.GONE);
                    holder.facing.setVisibility(View.VISIBLE);
                    holder.stock.setVisibility(View.GONE);*//*
            }*/


            final NewStockDataActivity.ViewHolder finalHolder = holder;
            holder.toggle_available.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (buttonView.isPressed()) {

                        editFlag = true;

                        if (isChecked) {
                            childData.setToggleValue("1");
                            //for Egypt
                            if (country_id.equals("6")) {
                                finalHolder.stock.setVisibility(View.VISIBLE);
                            } else {
                                finalHolder.stock.setVisibility(View.GONE);
                            }

                        /*childData.setStock("");
                        childData.setFacing("");*/
                        } else {
                       /* childData.setStock("");
                        childData.setFacing("");*/
                            childData.setToggleValue("0");
                            finalHolder.stock.setVisibility(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")) {
                                    childData.setStock("");
                                    childData.setFacing("");
                                }
                            }
                        }
                        expandableListView.clearFocus();
                        expandableListView.invalidateViews();
                    }
                }
            });

            if (childData.getToggleValue().equals("1")) {
                holder.toggle_available.setChecked(true);
                if (country_id.equals("6") && 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(View.VISIBLE);
            }


            holder.stock.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    final EditText caption = (EditText) v;
                    String edStock = caption.getText().toString().replaceFirst("^0+(?!$)", "");

                    /*if (!childData.getFacing().equals("") && Integer.parseInt(stock) >= 0 && Integer.parseInt(childData.getFacing()) < Integer.parseInt(stock)) {

                    }*/
                    editFlag = true;
                    if (!edStock.equals("")) {
                        String stock = edStock;

                        //for Egypt
                        if (country_id.equals("6") && 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(NewStockDataActivity.this);
                                    builder.setMessage(getString(R.string.check_faceup))
                                            .setCancelable(false)
                                            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int 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(NewStockDataActivity.this);
                                            builder.setMessage(getString(R.string.check_faceup))
                                                    .setCancelable(false)
                                                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int 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(NewStockDataActivity.this);
                                        builder.setMessage(getString(R.string.check_stock))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int 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(NewStockDataActivity.this);
                                        builder.setMessage(getString(R.string.check_stock))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        finalHolder.stock.setText("");
                                                        dialog.dismiss();
                                                        isDialogOpen = !isDialogOpen;
                                                    }
                                                });
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    }
                                }
                            }
                        }
                    } else {
                        childData.setStock("");
                    }
                }
            });
            holder.stock.setText(childData.getStock());


            final NewStockDataActivity.ViewHolder finalHolder1 = holder;
            final NewStockDataActivity.ViewHolder finalHolder2 = holder;
            holder.facing.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    final EditText caption = (EditText) v;
                    String edFaceup = caption.getText().toString().replaceFirst("^0+(?!$)", "");

                    editFlag = true;

                    if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                        //int num = Integer.parseInt(edFaceup);
                        double faceup = Double.parseDouble(edFaceup);
                        int num = (int) faceup;
                        //int faceint = (int)(faceup - Math.floor( 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);

                            }
                        }


                        /*Double faceup = Double.parseDouble(edFaceup);
                        DecimalFormat twoDForm = new DecimalFormat(".#");
                        faceup=  Double.valueOf(twoDForm.format(faceup));*/
                    }


                    boolean isFill = false;

                    //Toggle is no selected
                    if (childData.getToggleValue().equals("0")) {

                        //if stock is emplty
                        /*if (childData.getStock().equals("")) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
                            builder.setMessage(getString(R.string.msl_availability_new_stock_value))
                                    .setCancelable(false)
                                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                            AlertDialog alert = builder.create();
                            alert.show();
                        } else {*/
                        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("")) {

                                        //if (edFaceup != null && !edFaceup.equals("")) {

                                        String faceup = edFaceup.replaceFirst("^0+(?!$)", "");

                                        if (Double.parseDouble(faceup) <= Integer.parseInt(childData.getStock())) {

                                            isFill = true;

                          /*          if (!edFaceup.equals("")) {
                                        childData.setFacing(faceup);
                                    } else {
                                        childData.setFacing("");
                                    }*/
                                        } else {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
                                            builder.setMessage(getString(R.string.check_faceup))
                                                    .setCancelable(false)
                                                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int 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(NewStockDataActivity.this);
                                        builder.setMessage(getString(R.string.check_faceing))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int 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(NewStockDataActivity.this);
                                        builder.setMessage(getString(R.string.check_faceing))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                        finalHolder.facing.setText("");
                                                        dialog.dismiss();
                                                        isDialogOpen = !isDialogOpen;
                                                    }
                                                });
                                        AlertDialog alert = builder.create();
                                        alert.show();
                                    }
                                }
                            }

                        }
                        //}
                    } else {

                        if (country_id.equals("6")) {
                            if (!childData.getStock().equals("")) {

                                //if (edFaceup != null && !edFaceup.equals("")) {

                                String faceup = edFaceup.replaceFirst("^0+(?!$)", "");

                                if (edFaceup != null && !edFaceup.equals("") && !edFaceup.equals(".")) {
                                    if (Double.parseDouble(faceup) <= Integer.parseInt(childData.getStock())) {

                                        isFill = true;

                          /*          if (!edFaceup.equals("")) {
                                        childData.setFacing(faceup);
                                    } else {
                                        childData.setFacing("");
                                    }*/
                                    } else {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
                                        builder.setMessage(getString(R.string.check_faceup))
                                                .setCancelable(false)
                                                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int 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 toggle is yes then facing cannot be 0
                        if (childData.getCompany_id().equals("1") && childData.getMust_have().equals("1")
                                && !edFaceup.equals("") && edFaceup.equals("0")) {

                            AlertDialog.Builder builder = new AlertDialog.Builder(NewStockDataActivity.this);
                            builder.setMessage(getString(R.string.check_faceup_not_zero))
                                    .setCancelable(false)
                                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            finalHolder1.facing.setText("");
                                            dialog.dismiss();

                                        }
                                    });
                            AlertDialog alert = builder.create();
                            alert.show();
                        } 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+(?!$)", "");
                                //faceup = new DecimalFormat("##.#").format(Double.parseDouble(faceup));
                            }

                            // String str2 = PerfectDecimal(faceup, 3, 1);
                            childData.setFacing(faceup);
                        } else {
                            childData.setFacing("");
                        }
                    }

                }
            });

            holder.facing.setText(childData.getFacing());

            //empty check color change
            if (!checkflag) {
                boolean tempflag = false;

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

/*                                if (childData.getCompany_id().equals("1") && !childData.getMust_have().equals("0")) {
                                }else{
                                    holder.facing.setHint("");
                                }*/
                                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.cardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        // holder.lin_category.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        // holder.lin_category.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.lin_category.setBackgroundResource(R.drawable.cardview_error_border);
                    } else {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                        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.cardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        //holder.lin_category.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.lin_category.setBackgroundResource(R.drawable.cardview_error_border);
                    } else {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                        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;

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