package com.cpm.lorealbaautomation.dailyactivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

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

import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.appcompat.widget.Toolbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;

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

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

public class SuggestedStockActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    ArrayAdapter<CharSequence> axe_name_adapter, sub_axe_name_adapter, brand_name_adapter, product_name_adapter;
    Spinner sku_spin, brand_spin, sub_axe_spin, axe_spin;
    ArrayList<ProductMaster> brandList = new ArrayList<>();
    ArrayList<ProductMaster> subAxeList = new ArrayList<>();
    ArrayList<ProductMaster> axeList = new ArrayList<>();

    ExpandableListView lvExp_stock_check;
    FloatingActionButton fab_save;
    Lorealba_Database db;
    Context context;
    AlertDialog alert;
    private SharedPreferences preferences;
    String counter_id, visit_date, username, user_type, _pathforcheck, _path;
    ArrayList<ProductMaster> listDataHeader = new ArrayList<>();
    ArrayList<ProductMaster> childStockList = new ArrayList<>();
    HashMap<ProductMaster, List<ProductMaster>> listDataChild;
    boolean checkflag = true;
    ArrayList<Integer> checkHeaderArray = new ArrayList<>();
    ExpandableListAdapter listAdapter;
    String brandName = "";
    String axeName = "";
    String subAxeName = "";

    int groupPositionGlobal = -1;
    ProductMaster globalHeaderObject = new ProductMaster();

    EditText et_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suggested_stock);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        validateUIData();
        prepareListData();
        validate_spin_ui_data();
        listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        lvExp_stock_check.setAdapter(listAdapter);
    }

    private void validateUIData() {
        preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Report - Suggested Stock");
        sku_spin = (Spinner) findViewById(R.id.sku_spin);
        brand_spin = (Spinner) findViewById(R.id.stock_brand_spin);
        sub_axe_spin = (Spinner) findViewById(R.id.sub_axe_spin);
        axe_spin = (Spinner) findViewById(R.id.axe_spin);
        lvExp_stock_check = (ExpandableListView) findViewById(R.id.lvExp_stock_check);
        et_search = (EditText) findViewById(R.id.et_search);
        fab_save = (FloatingActionButton) findViewById(R.id.save_fab);
        fab_save.setOnClickListener(this);
        ImageView img_unfilled = (ImageView) findViewById(R.id.img_unfilled);
        img_unfilled.setVisibility(View.INVISIBLE);

        db.open();
        brandList = db.getsub_brand_name("1", "BrandName", false);
        subAxeList = db.getsub_brand_name("1", "SubAxeName", false);
        axeList = db.getsub_brand_name("1", "AxeName", false);

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                String text = s.toString();
                setSearchFilter(listAdapter.get_listDataHeader(), text, listAdapter.get_listDataChild());
            }

            @Override
            public void afterTextChanged(Editable s) {

                String text = s.toString();

            }
        });
    }

    public void setSearchFilter(List<ProductMaster> originalList, String text, HashMap<ProductMaster,
            List<ProductMaster>> listDataChild) {

        HashMap<ProductMaster, List<ProductMaster>> filterChildHashMap = new HashMap<>();

        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (int i = 0; i < originalList.size(); i++) {
            ProductMaster parent = originalList.get(i);
            List<ProductMaster> listChild = listDataChild.get(parent);
            List<ProductMaster> listFilterChild = new ArrayList<>();
            for (int j = 0; j < listChild.size(); j++) {
                if (listChild.get(j).getProductName().contains(text)) {
                    listFilterChild.add(listChild.get(j));
                } else {
                    continue;
                }
            }

            if (listFilterChild.size() > 0) {
                filterList.add(parent);
                filterChildHashMap.put(parent, listFilterChild);

            }

        }

        ExpandableListAdapter listAdapter = new ExpandableListAdapter(context, filterList, filterChildHashMap);
        lvExp_stock_check.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();


    }

    private void prepareListData() {
        db.open();
        listDataHeader = new ArrayList<>();
        listDataChild = new HashMap<>();
        //inserted data
        listDataHeader = db.getSuggestedStockHeaderInsertedData(visit_date);
        if (listDataHeader.size() == 0) {
            listDataHeader = db.getstock_check_axeandsub_axe("1");
        }

        boolean updateFlag = false;
        if (listDataHeader.size() > 0) {
            for (int i = 0; i < listDataHeader.size(); i++) {
                childStockList = db.getSuggestedInsertedData(listDataHeader.get(i).getAxeName(), listDataHeader.get(i).getSubAxeName(), listDataHeader.get(i).getBrandName());
                if (childStockList.size() > 0) {
                    updateFlag = true;

                } else {
                    childStockList = db.getbrand_wise_sku_fromStockData(listDataHeader.get(i).getSubAxeName(), listDataHeader.get(i).getAxeName(), listDataHeader.get(i).getBrandName(), "1");
                }

                listDataChild.put(listDataHeader.get(i), childStockList); // Header, Child data
            }

            if (updateFlag)
                fab_save.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.edit_txt));
        }
    }


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

        if (id == R.id.save_fab) {
            db.open();
            db.insertSuggestedStockCapturedData(visit_date, listDataChild, listDataHeader);
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);

        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

        if (adapterView.getId() == R.id.stock_brand_spin) {
            if (position != 0) {
                brandName = adapterView.getSelectedItem().toString();
                setFilter(FILTER_FOR_BRAND);
                axeList = db.getAxeNSubAxe("1", "AxeName", brandName, null);
                subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null);
                setAxeSpinnerData(axeList);
                setSubAxeSpinnerData(subAxeList);

            } else {
                brandName = "";
                setFilter(CLEAR_FILTER);
                axeList = db.getAxeNSubAxe("1", "AxeName", null, null);
                subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null);
                setAxeSpinnerData(axeList);
                setSubAxeSpinnerData(subAxeList);
            }

        }
        if (adapterView.getId() == R.id.axe_spin) {

            if (position != 0) {
                axeName = adapterView.getSelectedItem().toString();
                setFilter(FILTER_FOR_AXE);
                subAxeList = db.getAxeNSubAxe("1", "SubAxeName", "", axeName);
                setSubAxeSpinnerData(subAxeList);
            } else {
                axeName = "";
                if (brand_spin.getSelectedItemPosition() == 0) {
                    subAxeList = db.getAxeNSubAxe("1", "SubAxeName", null, null);
                    setSubAxeSpinnerData(subAxeList);
                    setFilter(CLEAR_FILTER);
                } else {
                    subAxeList = db.getAxeNSubAxe("1", "SubAxeName", brandName, null);
                    setSubAxeSpinnerData(subAxeList);
                    setFilter(FILTER_FOR_BRAND);
                }
            }

        } else if (adapterView.getId() == R.id.sub_axe_spin) {

            if (position != 0) {
                subAxeName = adapterView.getSelectedItem().toString();
                setFilter(FILTER_FOR_SUBAXE);
            } else {
                subAxeName = "";
                if (axe_spin.getSelectedItemPosition() == 0) {
                    if (brand_spin.getSelectedItemPosition() == 0) {
                        setFilter(CLEAR_FILTER);
                    } else {
                        setFilter(FILTER_FOR_BRAND);
                    }
                } else {
                    setFilter(FILTER_FOR_AXE);
                }
            }

        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    public ArrayList<ProductMaster> filterListForBrand(List<ProductMaster> originalList, String text) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getBrandName().equalsIgnoreCase(text)) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForAxe(List<ProductMaster> originalList, String text, String brandName) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }

    public ArrayList<ProductMaster> filterListForSubAxe(List<ProductMaster> originalList, String text, String brandName, String axeName) {
        ArrayList<ProductMaster> filterList = new ArrayList<>();
        for (ProductMaster object : originalList) {
            if (object.getSubAxeName().equalsIgnoreCase(text) && (brandName.equals("") || object.getBrandName().equalsIgnoreCase(brandName)) && (axeName.equals("") || object.getAxeName().equalsIgnoreCase(axeName))) {
                filterList.add(object);
            } else {
                continue;
            }
        }
        return filterList;
    }


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

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

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

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

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

        @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 ProductMaster childText = (ProductMaster) getChild(groupPosition, childPosition);
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_item_stock_entory, null);
                holder = new ViewHolder();
                holder.cardView = convertView.findViewById(R.id.card_view);
                holder.ed_Stock = convertView.findViewById(R.id.ed_Stock);
                holder.mrp = convertView.findViewById(R.id.mrp);
                holder.stock_img_plus = convertView.findViewById(R.id.stock_img_plus);
                holder.stock_img_minus = convertView.findViewById(R.id.stock_img_minus);
                convertView.setTag(holder);


            } else {

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

            TextView txtListChild = convertView.findViewById(R.id.lblListItem);
            txtListChild.setText(childText.getProductName() + " (MRP - ₹ " + childText.getMrp() + ")");

            holder.stock_img_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listAdapter.notifyDataSetChanged();
                    int minteger = childText.getStock();
                    ++minteger;

                    if (minteger <= 10) {
                        childText.setStock(minteger);
                        isDataAdded = true;
                    } else {
                        AlertandMessages.showToastMsg(context, "Stock cannot be greater than 10");
                    }
                }
            });

            holder.stock_img_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listAdapter.notifyDataSetChanged();
                    int minteger = childText.getStock();
                    --minteger;

                    if (minteger >= 0) {
                        childText.setStock(minteger);
                        isDataAdded = true;
                    } else {
                        AlertandMessages.showToastMsg(context, "Stock cannot be less than 0");
                    }

                }
            });
            holder.ed_Stock.setText(childText.getStock() + "");
            holder.ed_Stock.setId(childPosition);

            holder.mrp.setText(" MRP = " + childText.getMrp() + "");
            holder.mrp.setId(childPosition);

            return convertView;
        }

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

        @Override
        public Object getGroup(int groupPosition) {
            return this._listDataHeader.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return this._listDataHeader.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            final ProductMaster headerTitle = (ProductMaster) getGroup(groupPosition);
            if (convertView == null) {

                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.list_group_stock_entry, null);
            }
            TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
            ImageView stock_cam = (ImageView) convertView.findViewById(R.id.stock_cam);

            stock_cam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    groupPositionGlobal = groupPosition;
                    globalHeaderObject = headerTitle;
                    _pathforcheck = counter_id + "_suggested_stk_img" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(SuggestedStockActivity.this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            });

            if (headerTitle.getImagePath().equals("")) {
                stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera));
            } else {
                stock_cam.setImageDrawable(getResources().getDrawable(R.mipmap.camera_tick));
            }

            lblListHeader.setText(headerTitle.getAxeName() + " - " + headerTitle.getSubAxeName() + " - " + headerTitle.getBrandName());
            if (!checkflag) {
                if (checkHeaderArray.contains(groupPosition)) {
                    lblListHeader.setBackgroundColor(getResources().getColor(R.color.red));
                } else {
                    lblListHeader.setBackgroundColor(getResources().getColor(R.color.dashboard_ach));
                }

            } else {
                lblListHeader.setBackgroundColor(getResources().getColor(R.color.dashboard_ach));
            }
            return convertView;
        }

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

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

    public class ViewHolder {
        TextView ed_Stock, mrp;
        Button stock_img_plus, stock_img_minus;
        CardView cardView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void validate_spin_ui_data() {
        brand_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        brand_name_adapter.add("- Brand -");

        for (int i = 0; i < brandList.size(); i++) {
            brand_name_adapter.add(brandList.get(i).getBrandName());
        }

        brand_spin.setAdapter(brand_name_adapter);
        brand_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

        setAxeSpinnerData(axeList);
        setSubAxeSpinnerData(axeList);

        axe_spin.setOnItemSelectedListener(this);
        sub_axe_spin.setOnItemSelectedListener(this);
        brand_spin.setOnItemSelectedListener(this);

    }

    private void setAxeSpinnerData(ArrayList<ProductMaster> axeList) {
        axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        axe_name_adapter.add("- Axe Name -");

        for (int i = 0; i < axeList.size(); i++) {
            axe_name_adapter.add(axeList.get(i).getBrandName());
        }

        axe_spin.setAdapter(axe_name_adapter);
        axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

    }

    private void setSubAxeSpinnerData(ArrayList<ProductMaster> subAxeList) {
        sub_axe_name_adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_item);
        sub_axe_name_adapter.add("- Sub Axe Name -");


        for (int i = 0; i < subAxeList.size(); i++) {
            sub_axe_name_adapter.add(subAxeList.get(i).getBrandName());
        }

        sub_axe_spin.setAdapter(sub_axe_name_adapter);
        sub_axe_name_adapter.setDropDownViewResource(R.layout.spinner_custom_item);

    }

    public void setFilter(int filterType) {

        if (filterType == FILTER_FOR_BRAND) {
            listAdapter = new ExpandableListAdapter(context, filterListForBrand(listDataHeader, brandName), listDataChild);
        } else if (filterType == FILTER_FOR_AXE) {
            listAdapter = new ExpandableListAdapter(context, filterListForAxe(listDataHeader, axeName, brandName), listDataChild);
        } else if (filterType == FILTER_FOR_SUBAXE) {
            listAdapter = new ExpandableListAdapter(context, filterListForSubAxe(listDataHeader, subAxeName, brandName, axeName), listDataChild);
        } else {
            listAdapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        }

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

    final int FILTER_FOR_BRAND = 1;
    final int FILTER_FOR_AXE = 2;
    final int FILTER_FOR_SUBAXE = 3;
    final int CLEAR_FILTER = 0;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == android.R.id.home) {
            isChanged();
        }


        return super.onOptionsItemSelected(item);
    }

    boolean isDataAdded = false;

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

    void isChanged() {
        if (isDataAdded) {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
            builder.setTitle("Parinaam");
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            finish();
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
            android.app.AlertDialog alert = builder.create();
            alert.show();
        } else {
            super.onBackPressed();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

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

            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;

            case -1:
                if (_pathforcheck != null && !_pathforcheck.equals("")) {
                    if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                        convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                        isDataAdded = true;
                        globalHeaderObject.setImagePath(_pathforcheck);
                        groupPositionGlobal = -1;
                        _pathforcheck = "";
                        listAdapter.notifyDataSetChanged();
                    }
                }

                break;
        }

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


}
