package cpm.com.gskmtorange.dailyentry;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;

public class StockPricingActivity extends AppCompatActivity {
    private Context context;
    ExpandableListView expandableListView;
    private SharedPreferences preferences;

    String categoryName, categoryId, 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;
    GSKOrangeDB db;

    ArrayList<MSL_AvailabilityStockFacingGetterSetter> headerDataList;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> childDataList = new ArrayList<>();
    List<MSL_AvailabilityStockFacingGetterSetter> hashMapListHeaderData;
    HashMap<MSL_AvailabilityStockFacingGetterSetter, List<MSL_AvailabilityStockFacingGetterSetter>> hashMapListChildData;
    ExpandableListAdapter adapter;

    List<Integer> checkHeaderArray = new ArrayList<>();
    boolean checkflag = true;

    FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_pricing);
        Toolbar toolbar = findViewById(R.id.toolbar);

        expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);

        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_stock_pricing));
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        prepareList();
    }

    private void prepareList() {
        try {
            hashMapListHeaderData = new ArrayList<>();
            hashMapListChildData = new HashMap<>();

            //Header
            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);
                    //  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,"0");
                    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, "0", visit_date, false);

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

            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 (Exception e) {
            e.printStackTrace();
        }


    }

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

            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_stock_pricing, 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.et_price = (EditText) convertView.findViewById(R.id.et_price);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

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

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

            final ViewHolder finalHolder = holder;

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

                        if (!edStock.equals("")) {
                            String stock = edStock;

                            childData.setStock(stock);
                        } else {
                            childData.setStock("");
                        }
                    }
                }
            });
            holder.et_price.setText(childData.getStock());

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

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

                    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));
                        }
                    }
                } else {
                    if (holder.et_price.getText().toString().equals("")) {
                        holder.et_price.setBackgroundColor(getResources().getColor(R.color.white));
                        holder.et_price.setHintTextColor(getResources().getColor(android.R.color.holo_red_dark));
                        holder.et_price.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;
        LinearLayout lin_category;
        EditText et_price;
    }
}
