package it.integry.integrywmsnative.gest.accettazione_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.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.accettazione_ordine_inevaso.dto.AccettazioneOrdineInevasoListViewModel;

/**
 * Created by GiuseppeS on 21/03/2018.
 */

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

    private Context mContext;
    private List<AccettazioneOrdineInevasoListViewModel> mDataset;
    private View mEmptyView;

    private ObservableArrayList<AccettazioneOrdineInevasoListViewModel> mObservableDataset;
    private IOnOrdineAccettazioneRowDispatchCallback 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 MainListOrdineAccettazioneAdapter(Context context, ObservableArrayList<AccettazioneOrdineInevasoListViewModel> 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(IOnOrdineAccettazioneRowDispatchCallback ordineRowDispatch) {
        mOrdineRowDispatch = ordineRowDispatch;
    }

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

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

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

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

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

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


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

        //v.setHasTransientState(true);

        ViewHolder vh = new ViewHolder(v);

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

        LinearLayout groupItemContainer = v.findViewById(R.id.accettazione_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(MainListOrdineAccettazioneAdapter.ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element

        ((TextView)holder.mGroupTitle).setText(mDataset.get(position).descrizioneGroup);

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

        int visibleElementsCounter = 0;

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

            final AccettazioneOrdineInevasoListViewModel.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.accettazione_ordine_inevaso_main_list___cod_art_for_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.accettazione_ordine_inevaso_main_list_group_item_badge1);
                badge1.setText(rowItem.getBadge1());

                final TextView badge2 = groupModelView.findViewById(R.id.accettazione_ordine_inevaso_main_list_group_item_badge2);
                badge2.setText(rowItem.getBadge2());


                final TextView descrizione = groupModelView.findViewById(R.id.accettazione_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 qtaEvasa = groupModelView.findViewById(R.id.accettazione_ordine_inevaso_main_list_group_item_qta_evasa);
                qtaEvasa.setText(UtilityNumber.decimalToString(rowItem.getQtaRiservata()));

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


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

                holder.mLinearLayoutGroupItemContainer.addView(groupModelView);
            }
        }

    }

    @Override
    public void onViewRecycled(MainListOrdineAccettazioneAdapter.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);
        }
    }
}
