package cpm.com.gskmtorange.dailyentry;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
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.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

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

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.gsk_dailyentry.MSL_Availability_StockFacingActivity;
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.PharmaMSLInsertedGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.StockFacing_PlanogramTrackerDataGetterSetter;

public class OrderTakingActivity extends AppCompatActivity implements DialogCallbackListener {
    ExpandableListView expandableListView;
    private Context context;
    TextView txt_mslAvailabilityName;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> headerDataList;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> childDataList;
    List<MSL_AvailabilityStockFacingGetterSetter> hashMapListHeaderData;

    String _pathforcheck1, _pathforcheck2, _pathforcheck3, _path, str, msg;

    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 gallery_package = "";
    Uri outputFileUri;

    String str_planogram = "", _pathforcheck = "";
    EditText storepoET,podateET;

    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;
    RadioButton radio_yes,radio_no;
    RadioGroup radio_group;
    String isExist="";
    String sys_po_number="";
    TextView sys_gen_poTV;
    LinearLayout poLL,pocamLL;
    String storepo ="";
    ImageView poIV;
    String img_str="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            //setContentView(R.layout.activity_msl__availability_stock_facing);
            setContentView(R.layout.activity_order_taking);
            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);
            poIV = (ImageView) findViewById(R.id.poIV);
            pocamLL =  findViewById(R.id.pocamLL);
            poLL = findViewById(R.id.poLL);

            radio_group =findViewById(R.id.radio_group);
            radio_yes = findViewById(R.id.radio_yes);
            radio_no =  findViewById(R.id.radio_no);
            sys_gen_poTV =  findViewById(R.id.sys_gen_poTV);

            storepoET = findViewById(R.id.storepoET);
            podateET = findViewById(R.id.podateET);

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

            str = CommonString.getImagesFolder(context);


            //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.order_taking));
            setSupportActionBar(toolbar);

            String [] str = date.split("/");
            String str1 = str[0];
            String str2 = str[1];
            String str3 = str[2];
            sys_po_number = store_id + "-" +str3+str1+str2;
            sys_gen_poTV.setText(sys_po_number);

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            str_planogram = CommonString.getDownloadedImageFolder(context);
            podateET.setText(visit_date);
            prepareList();


            //Camera
         //   prepareDefaultList();
         //   cameraMethod();

            final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

            poIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    _pathforcheck = store_id + categoryId + "POImage_" + date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";

                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    intime = CommonFunctions.getCurrentTimeWithLanguage(context);
                    startCameraActivity();
                }
            });

            radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int i) {
                    if (radio_yes.isChecked()) {
                        radio_yes.setBackground(getResources().getDrawable(R.mipmap.yes_green));
                        radio_no.setBackground(getResources().getDrawable(R.mipmap.no_white));
                        poLL.setVisibility(View.VISIBLE);
                        if(country_id.equals("17")){
                            pocamLL.setVisibility(View.VISIBLE);
                        }
                        else{
                            pocamLL.setVisibility(View.GONE);
                        }
                        isExist="yes";
                        /*expListView.setVisibility(View.VISIBLE);
                        categoryobject.setIsChecked(1);
                        skuData.get(0).setIsChecked(1);*/
                    }
                    if (radio_no.isChecked()) {
                        radio_no.setBackground(getResources().getDrawable(R.mipmap.no_red));
                        radio_yes.setBackground(getResources().getDrawable(R.mipmap.yes_white));
                        poLL.setVisibility(View.GONE);
                        pocamLL.setVisibility(View.GONE);
                        isExist="no";
                        img_str = "";
                        /*expListView.setVisibility(View.GONE);
                        categoryobject.setIsChecked(0);
                        skuData.get(0).setIsChecked(0);*/
                    }
                }
            });
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
                    expandableListView.clearFocus();
                    adapter.notifyDataSetChanged();
                    storepo = storepoET.getText().toString();
                    //Log.e("storepo",storepo);
                    if(isExist.equalsIgnoreCase("no")){
                        if (db.checkOrder_taking_Data(store_id, categoryId)) {
                            db.updateOrder_taking_data(img_str,isExist,storepo,sys_po_number,date,store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                            Toast.makeText(context,getResources().getString(R.string.update_message),Toast.LENGTH_SHORT).show();
                        } else {
                            db.InsertOrderTakingData(img_str,isExist,storepo,sys_po_number,date,store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                            Toast.makeText(context,getResources().getString(R.string.save_message),Toast.LENGTH_SHORT).show();
                        }

                        /*String pharma_msl_xml = "";
                        String onXML = "";
                        String _onxml = "";
                        String categoryxml = "";

                        db.open();
                        ArrayList<MSL_AvailabilityStockFacingGetterSetter> ordertakinglist = db.getOrder_TAKING_UploadServerData(store_id);
                        db.open();
                        ArrayList<MSL_AvailabilityStockFacingGetterSetter> getOrder_TAKING_CategoryData = db.getOrder_TAKING_CategoryData(store_id);

                        if (ordertakinglist.size() > 0) {
                            for(int k = 0; k < getOrder_TAKING_CategoryData.size(); k++){
                                _onxml = "[CATEGORY_DATA]"
                                        + "[MID]" + 0 + "[/MID]"
                                        + "[USERID]" + username + "[/USERID]"
                                        + "[PRESENT]" + getOrder_TAKING_CategoryData.get(k).getIsExist() + "[/PRESENT]"
                                        + "[CATEGORY_ID]" + getOrder_TAKING_CategoryData.get(k).getCategory_id() + "[/CATEGORY_ID]"
                                        + "[/CATEGORY_DATA]";
                                categoryxml = categoryxml + _onxml;
                            }
                            String cat_xml = categoryxml;

                            for (int j = 0; j < ordertakinglist.size(); j++) {
                                if(ordertakinglist.get(j).getIsExist()==1){
                                    onXML = "[ORDERDATA]"
                                            + "[MID]" + 0 + "[/MID]"
                                            + "[USERID]" + username + "[/USERID]"
                                            + "[PRESENT]" + ordertakinglist.get(j).getIsExist() + "[/PRESENT]"
                                            + "[SYSTEM_PO_NUM]" + ordertakinglist.get(j).getSys_PO_No() + "[/SYSTEM_PO_NUM]"
                                            + "[STORE_PO_NUM]" + ordertakinglist.get(j).getStore_PO_No() + "[/STORE_PO_NUM]"
                                            + "[PO_DATE]" + ordertakinglist.get(j).getPO_Date() + "[/PO_DATE]"
                                            + "[SKU_ID]" + ordertakinglist.get(j).getSku_id() + "[/SKU_ID]"
                                            + "[ORDER_QTY]" + ordertakinglist.get(j).getFacing() + "[/ORDER_QTY]"+
                                            "[/ORDERDATA]";
                                    pharma_msl_xml = pharma_msl_xml + onXML;
                                }
                            }
                            String data_xml = cat_xml + pharma_msl_xml;

                            final String sos_xml = "[DATA]"  + data_xml + "[/DATA]";
                            Log.e("order_xml",sos_xml);
                        }*/

                        finish();
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    }
                    else{
                        if(validation()){
                            if (validateData(hashMapListHeaderData, hashMapListChildData)) {
                                db.open();
                                if (db.checkOrder_taking_Data(store_id, categoryId)) {
                                    db.updateOrder_taking_data(img_str,isExist,storepo,sys_po_number,date,store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                                    Toast.makeText(context,getResources().getString(R.string.update_message),Toast.LENGTH_SHORT).show();

                                } else {
                                    db.InsertOrderTakingData(img_str,isExist,storepo,sys_po_number,date,store_id, categoryId, hashMapListHeaderData, hashMapListChildData);
                                    Toast.makeText(context,getResources().getString(R.string.save_message),Toast.LENGTH_SHORT).show();
                                }
                                finish();
                                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);

                                String pharma_msl_xml = "";
                                String onXML = "";

                                // db.open();
                                ArrayList<MSL_AvailabilityStockFacingGetterSetter> ordertakinglist = db.getOrder_TAKING_UploadServerData(store_id);
                                ArrayList<MSL_AvailabilityStockFacingGetterSetter> getOrder_TAKING_CategoryData = db.getOrder_TAKING_CategoryData(store_id);
                                String _onxml = "";
                                String categoryxml = "";
                                if (ordertakinglist.size() > 0) {
                                    for(int k = 0; k < getOrder_TAKING_CategoryData.size(); k++){
                                        _onxml = "[CATEGORY_DATA]"
                                                + "[MID]" + 0 + "[/MID]"
                                                + "[USERID]" + username + "[/USERID]"
                                                + "[PRESENT]" + getOrder_TAKING_CategoryData.get(k).getIsExist() + "[/PRESENT]"
                                                + "[CATEGORY_ID]" + getOrder_TAKING_CategoryData.get(k).getCategory_id() + "[/CATEGORY_ID]"
                                                + "[/CATEGORY_DATA]";
                                        categoryxml = categoryxml + _onxml;
                                    }
                                    String cat_xml = categoryxml;

                                    for (int j = 0; j < ordertakinglist.size(); j++) {
                                        if(ordertakinglist.get(j).getIsExist()==1){
                                            if(!ordertakinglist.get(j).getFacing().equals("0") &&
                                                    !ordertakinglist.get(j).getFacing().equals("")) {
                                                onXML = "[ORDERDATA]"
                                                        + "[MID]" + 0 + "[/MID]"
                                                        + "[USERID]" + username + "[/USERID]"
                                                        + "[PRESENT]" + ordertakinglist.get(j).getIsExist() + "[/PRESENT]"
                                                        + "[SYSTEM_PO_NUM]" + ordertakinglist.get(j).getSys_PO_No() + "[/SYSTEM_PO_NUM]"
                                                        + "[STORE_PO_NUM]" + ordertakinglist.get(j).getStore_PO_No() + "[/STORE_PO_NUM]"
                                                        + "[PO_IMAGE]" + ordertakinglist.get(j).getPO_Img() + "[/PO_IMAGE]"
                                                        + "[PO_DATE]" + ordertakinglist.get(j).getPO_Date() + "[/PO_DATE]"
                                                        + "[SKU_ID]" + ordertakinglist.get(j).getSku_id() + "[/SKU_ID]"
                                                        + "[ORDER_QTY]" + ordertakinglist.get(j).getFacing() + "[/ORDER_QTY]" +
                                                        "[/ORDERDATA]";
                                                pharma_msl_xml = pharma_msl_xml + onXML;
                                            }
                                        }
                                    }
                                    String data_xml = cat_xml + pharma_msl_xml;

                                    final String sos_xml = "[DATA]"  + data_xml + "[/DATA]";
                                    Log.e("order_xml",sos_xml);
                                }

                            } else {
                                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(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();
        }
    }

    private boolean validation() {
        boolean flag = true;
        if(img_str.equals("") && country_id.equals("17")){
            flag = false;
            Toast.makeText(context, context.getString(R.string.pls_capture_img), Toast.LENGTH_SHORT).show();
        }
        else{
            flag = true;
        }
        return flag;
    }

    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;
        int qtysum = 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 faceup = data.getFacing();
                if(faceup!=null && !faceup.equals("")){
                    qtysum =qtysum+Integer.parseInt(faceup);
                }

                //Company_id
                if (listDataChild.get(listDataHeader.get(i)).get(j).getCompany_id().equals("1") && !country_id.equals("17")) {
                    if (store_flag_hide.equals("0")) {
                        if (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);
                            Toast.makeText(context, context.getString(R.string.pls_fill_order_qty), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                if (!child_flag)
                    listTemp.add(data);

            }

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

        if(qtysum==0){
            all_flag = false;
            //flag = false;
            Toast.makeText(context, "At least one order qty should be greater than zero", Toast.LENGTH_SHORT).show();
            adapter.notifyDataSetChanged();
            /*adapter = new ExpandableListAdapter(this, listDataHeaderTemp, listDataChildTemp);
            expandableListView.setAdapter(adapter);
            checkflag = false;*/
        }

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

        return all_flag;
    }


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

    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.getOrderTaking_StockFacingHeaderData(country_id,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.getOrderTaking_StockFacingHeaderData(country_id,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.getOrderTaking_StockFacingHeaderData(country_id,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.getOrder_TAKING_SKU_AfterSaveData(categoryId, headerDataList.get(i).getBrand_id(), store_id);
                    //Log.e("childlistsize", String.valueOf(childDataList.size()));
                   // childDataList = db.getMSL_Availability_StockFacingSKU_AfterSaveData(categoryId, headerDataList.get(i).getBrand_id(), store_id);
                    if (!(childDataList.size() > 0)) {
                        if (country_id.equals("7") || country_id.equals("8") || country_id.equals("17")) {
                            childDataList = db.getORDERTAKING_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.getORDERTAKING_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);
                        } else {
                            childDataList = db.getORDERTAKING_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);
                        }
                    }
                    else{
                        //if(childDataList.get(0).getPO_Date())
                       // podateET.setText(childDataList.get(0).getPO_Date());
                        sys_gen_poTV.setText(childDataList.get(0).getSys_PO_No());
                        storepoET.setText(childDataList.get(0).getStore_PO_No());
                        Log.d("childlistdata",childDataList.get(0).getPO_Img());
                        if(childDataList.get(0).getPO_Img()!=null && !childDataList.get(0).getPO_Img().equals("")){
                            img_str = childDataList.get(0).getPO_Img();
                            poIV.setImageResource(R.mipmap.camera_green);
                        }
                        if(childDataList.get(0).getIsExist()==1){
                            radio_yes.setChecked(true);
                            radio_yes.setBackground(getResources().getDrawable(R.mipmap.yes_green));
                            radio_no.setBackground(getResources().getDrawable(R.mipmap.no_white));
                            poLL.setVisibility(View.VISIBLE);
                            isExist="yes";
                            podateET.setText(visit_date);
                        }
                        else if(childDataList.get(0).getIsExist()==0){
                            radio_no.setChecked(true);
                            radio_no.setBackground(getResources().getDrawable(R.mipmap.no_red));
                            radio_yes.setBackground(getResources().getDrawable(R.mipmap.yes_white));
                            poLL.setVisibility(View.GONE);
                            isExist="no";
                        }
                        else{
                            radio_yes.setBackground(getResources().getDrawable(R.mipmap.yes_white));
                            radio_no.setBackground(getResources().getDrawable(R.mipmap.no_white));
                            poLL.setVisibility(View.VISIBLE);
                            isExist="";
                        }
                    }
                    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();
        }
    }

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

    }

    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_order_taking, 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);
            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_order_taking_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")) {
                holder.facing.setVisibility(View.GONE);
                holder.facing_view.setVisibility(View.GONE);
            } else {
                holder.facing.setVisibility(View.VISIBLE);
                holder.facing_view.setVisibility(View.VISIBLE);
            }
            //usk
           /* 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);
            }*/

            holder.txt_skuName.setText(childData.getSku());

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

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



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


            final ViewHolder finalHolder1 = holder;
            final 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);
                            }
                        }
                    }

                    boolean isFill = false;

                    //Toggle is no selected

                        if (country_id.equals("6")) {
                            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(OrderTakingActivity.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 (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 (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 (childData.getCompany_id().equals("1")) {
                    holder.facing.setHint("");

                    if (tempflag) {
                        holder.lin_category.setBackgroundResource(R.drawable.cardview_error_border);
                    } else {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                        if (childData.getCompany_id().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 {
                        //holder.cardView.setCardBackgroundColor(getResources().getColor(R.color.white));
                        if (childData.getCompany_id().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;
    }

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

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

    }


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

        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;

            case 0:

                if (_pathforcheck != null && !_pathforcheck.equals("")) {
                    if (new File(str + _pathforcheck).exists()) {
                      Log.d("imagepath", str + _pathforcheck);
                        poIV.setImageResource(R.mipmap.camera_green);
                        img_str = _pathforcheck;
                        _pathforcheck = "";
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (editFlag) {
                CommonFunctions.showAlertDialog(OrderTakingActivity.this, getResources().getString(R.string.data_will_be_lost));
            } else {
                finish();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            }
            //finish();
        }

        return super.onOptionsItemSelected(item);
    }

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

    protected void startCameraActivity() {
        try {
            Log.i("MakeMachine", "startCameraActivity()");
            File file = new File(_path);
            outputFileUri =  FileProvider.getUriForFile(context, "cpm.com.gskmtorange.fileprovider", file);

            String defaultCameraPackage = "";
            final PackageManager packageManager = getPackageManager();
            List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
            for (int n = 0; n < list.size(); n++) {
                if ((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                    Log.e("TAG", "Installed Applications  : " + list.get(n).loadLabel(packageManager).toString());
                    Log.e("TAG", "package name  : " + list.get(n).packageName);

                    //temp value in case camera is gallery app above jellybean
                    String packag = list.get(n).loadLabel(packageManager).toString();
                    if (packag.equalsIgnoreCase("Gallery") || packag.equalsIgnoreCase("Galeri") || packag.equalsIgnoreCase("الاستوديو")) {
                        gallery_package = list.get(n).packageName;
                    }

                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {
                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    } else {

                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {

                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    }
                }
            }

            //com.android.gallery3d

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(defaultCameraPackage);
            startActivityForResult(intent, 0);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(gallery_package);
            startActivityForResult(intent, 0);

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

}