package it.integry.integrywmsnative.gest.vendita_ordine_inevaso.core;

import android.content.Context;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import android.graphics.Color;
import androidx.core.util.Pools;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.annimon.stream.Stream;

import java.util.ArrayList;
import java.util.List;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.CommonConst;
import it.integry.integrywmsnative.core.utility.UtilityNumber;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.gest.vendita.dto.PickingObjectDTO;
import it.integry.integrywmsnative.gest.vendita_ordine_inevaso.core.interfaces.IOnOrdineVenditaRowDispatched;
import it.integry.integrywmsnative.gest.vendita_ordine_inevaso.dto.VenditaOrdineInevasoListViewModel;

public class MainListOrdineVenditaInevasoAdapter extends RecyclerView.Adapter<MainListOrdineVenditaInevasoAdapter.ViewHolder> {

    private Context mContext;
    private List<VenditaOrdineInevasoListViewModel> mDataset;
    private View mEmptyView;
    private ObservableArrayList<VenditaOrdineInevasoListViewModel> mObservableDataset;
    private IOnOrdineVenditaRowDispatched mOrdineRowDispatch;

    private static final Pools.SynchronizedPool sPool = new Pools.SynchronizedPool(200);

    public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        protected View mGroupTitle;
        protected LinearLayout mLinearLayoutGroupItemContainer;

        protected List<View> pool = new ArrayList<>();

        public ViewHolder(View v) {
            super(v);
        }
    }

    public MainListOrdineVenditaInevasoAdapter(Context context, ObservableArrayList<VenditaOrdineInevasoListViewModel> myDataset, View emptyView) {
        mContext = context;
        mObservableDataset = myDataset;
        mEmptyView = emptyView;


        mDataset = Stream.of(mObservableDataset).filter(x -> !x.isHidden()).toList();
        mObservableDataset.addOnListChangedCallback(onListChangedCallback);

        checkIfEmpty();
    }

    public void setOnOrdineRowDispatchCallback(IOnOrdineVenditaRowDispatched ordineRowDispatch) {
        mOrdineRowDispatch = ordineRowDispatch;
    }

    private ObservableList.OnListChangedCallback onListChangedCallback = new ObservableList.OnListChangedCallback<ObservableList<VenditaOrdineInevasoListViewModel>>() {
        @Override
        public void onChanged(ObservableList<VenditaOrdineInevasoListViewModel> sender) {
            refreshNotHiddenElements();
            notifyDataSetChanged();
            checkIfEmpty();
        }

        @Override
        public void onItemRangeChanged(ObservableList<VenditaOrdineInevasoListViewModel> sender, int positionStart, int itemCount) {
            refreshNotHiddenElements();
            notifyDataSetChanged();
            checkIfEmpty();
        }

        @Override
        public void onItemRangeInserted(ObservableList<VenditaOrdineInevasoListViewModel> sender, int positionStart, int itemCount) {
            refreshNotHiddenElements();
            notifyDataSetChanged();
            checkIfEmpty();
        }

        @Override
        public void onItemRangeMoved(ObservableList<VenditaOrdineInevasoListViewModel> sender, int fromPosition, int toPosition, int itemCount) {
            refreshNotHiddenElements();
            notifyDataSetChanged();
            checkIfEmpty();
        }

        @Override
        public void onItemRangeRemoved(ObservableList<VenditaOrdineInevasoListViewModel> sender, int positionStart, int itemCount) {
            refreshNotHiddenElements();
            notifyDataSetChanged();
            checkIfEmpty();
        }

        private void refreshNotHiddenElements() {
            mDataset = Stream.of(mObservableDataset).filter(x -> !x.isHidden()).toList();
        }
    };


    @Override
    public MainListOrdineVenditaInevasoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.vendita_ordine_inevaso_main_list_model, parent, false);


        ViewHolder vh = new ViewHolder(v);

        TextView descrizioneArtForn = v.findViewById(R.id.vendita_ordine_inevaso_main_list__descrizione_gruppo);
        vh.mGroupTitle = descrizioneArtForn;

        LinearLayout groupItemContainer = v.findViewById(R.id.vendita_ordine_inevaso_main_list__group_item_container);
        vh.mLinearLayoutGroupItemContainer = groupItemContainer;

        return vh;
    }


    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(MainListOrdineVenditaInevasoAdapter.ViewHolder holder, int position) {
        ((TextView)holder.mGroupTitle).setText(mDataset.get(position).descrizioneGroup);

        List<VenditaOrdineInevasoListViewModel.SubItem> subset = mDataset.get(position).rows;

        int visibleElementsCounter = 0;

        for(int i = 0; i < subset.size(); i++) {

            final VenditaOrdineInevasoListViewModel.SubItem rowItem = subset.get(i);

            if(!rowItem.getOriginalModel().isHidden() &&
                    (rowItem.getOriginalModel().isTempHidden() == null ||
                            (rowItem.getOriginalModel().isTempHidden() != null && !rowItem.getOriginalModel().isTempHidden()))) {
                visibleElementsCounter++;

                View groupModelViewPool = (View) sPool.acquire();
                if (groupModelViewPool == null) {
                    groupModelViewPool = LayoutInflater.from(mContext)
                            .inflate(R.layout.vendita_ordine_inevaso_main_list_child_group_model, holder.mLinearLayoutGroupItemContainer, false);
                }

                View groupModelView = groupModelViewPool;
                holder.pool.add(groupModelView);

                if (rowItem.getQtaRiservata().subtract(rowItem.getQtaOrdinata()).floatValue() >= 0 ) {
                    groupModelView.setBackgroundColor(mContext.getResources().getColor(R.color.green_500_with_alpha));
                } else if (rowItem.getQtaRiservata().floatValue() > 0) {
                    groupModelView.setBackgroundColor(mContext.getResources().getColor(R.color.orange_600_with_alpha));
                } else if (visibleElementsCounter % 2 == 1) {
                    groupModelView.setBackgroundColor(Color.WHITE);
                } else {
                    groupModelView.setBackgroundColor(mContext.getResources().getColor(R.color.letturaFacilitataBG));
                }

                final TextView badge1 = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_badge1);
                badge1.setText(rowItem.getBadge1());

                final TextView badge2 = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_badge2);
                badge2.setText(rowItem.getBadge2());
                badge2.setVisibility(UtilityString.isNullOrEmpty(rowItem.getBadge2()) ? View.GONE : View.VISIBLE);


                final TextView descrizione = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_descrizione);

                String descrizioneString = rowItem.getDescrizione();
                int descrizioneColor = Color.BLACK;

                if (UtilityString.isNullOrEmpty(descrizioneString)) {
                    descrizioneString = mContext.getString(R.string.no_description);
                    descrizioneColor = Color.GRAY;
                } else if (descrizioneString.equalsIgnoreCase(CommonConst.Config.COMMESSA_MAG)) {
                    descrizioneString = mContext.getString(R.string.stock);
                }

                descrizione.setText(descrizioneString);
                descrizione.setTextColor(descrizioneColor);

                final TextView subDescrizione1 = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_subdescrizione1);
                if(rowItem.getSubDescrizione1() != null) subDescrizione1.setText(Html.fromHtml(rowItem.getSubDescrizione1()));
                subDescrizione1.setVisibility(UtilityString.isNullOrEmpty(rowItem.getSubDescrizione1()) ? View.GONE : View.VISIBLE);

                final TextView subDescrizione2 = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_subdescrizione2);
                if(rowItem.getSubDescrizione2() != null) subDescrizione2.setText(Html.fromHtml(rowItem.getSubDescrizione2()));
                subDescrizione2.setVisibility(UtilityString.isNullOrEmpty(rowItem.getSubDescrizione2()) ? View.GONE : View.VISIBLE);

                final TextView qtaEvasa = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_qta_evasa);
                qtaEvasa.setText(UtilityNumber.decimalToString(rowItem.getQtaRiservata()));

                final TextView qtaTot = groupModelView.findViewById(R.id.vendita_ordine_inevaso_main_list_group_item_qta_tot);
                qtaTot.setText(UtilityNumber.decimalToString(rowItem.getQtaOrdinata()));


                groupModelView.setOnClickListener(view -> {
                    if (mOrdineRowDispatch != null) {
//                        rowItem.getOriginalModel().setTempEan128Model(null);
                        mOrdineRowDispatch.onOrdineRowDispatch(rowItem.getOriginalModel());
                    }
                });

                holder.mLinearLayoutGroupItemContainer.addView(groupModelView);

            }

        }

    }



    @Override
    public void onViewRecycled(MainListOrdineVenditaInevasoAdapter.ViewHolder holder){
        if(holder != null){
            for(int i = 0; i < holder.pool.size(); i++){
                ((ViewGroup) holder.pool.get(i).getParent()).removeView(holder.pool.get(i));
                sPool.release(holder.pool.get(i));
            }

            holder.pool.clear();
        }

        super.onViewRecycled(holder);
    }



    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }


    void checkIfEmpty() {
        if (mEmptyView != null) {
            final boolean emptyViewVisible = getItemCount() == 0;
            mEmptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
        }
    }

    public interface IOnOrdineRowDispatchCallback {

        void onOrdineRowDispatch(PickingObjectDTO item);

    }

}
