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

import android.content.Context;
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.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.gest.accettazione.dto.OrdineAccettazioneGroupedInevasoDTO;

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

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

    private Context mContext;
    private List<OrdineAccettazioneGroupedInevasoDTO> mDataset;
    private RunnableArgs<OrdineAccettazioneGroupedInevasoDTO> mOnGroupSelected;

    private Pools.SynchronizedPool sPool = new Pools.SynchronizedPool(2000);
    private Pools.SynchronizedPool sPoolClienti = new Pools.SynchronizedPool(3000);

    public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        private TextView mTextViewGroupHeader;
        private LinearLayout mLinearLayoutGroupItemContainer;

        private List<View> views = new ArrayList<>();

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

    // Provide a suitable constructor (depends on the kind of dataset)
    public MainListAccettazioneAdapter(Context context, List<OrdineAccettazioneGroupedInevasoDTO> myDataset, RunnableArgs<OrdineAccettazioneGroupedInevasoDTO> onGroupSelected) {
        mContext = context;
        mDataset = myDataset;
        mOnGroupSelected = onGroupSelected;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MainListAccettazioneAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.accettazione_main_list_model, parent, false);

        ViewHolder vh = new ViewHolder(v);

        TextView groupHeader = v.findViewById(R.id.accettazione_main_list_group_header);
        vh.mTextViewGroupHeader = groupHeader;

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

        final List<OrdineAccettazioneGroupedInevasoDTO.Ordine> subGroup = mDataset.get(position).ordini;
        final int finalPosition = position;

        holder.mTextViewGroupHeader.setText(mDataset.get(position).nomeFornitore);
        holder.itemView.setOnClickListener(view -> {
            boolean newValue = true;

            for(int i = 0; i < subGroup.size(); i++){
                if(subGroup.get(i).checkBox) newValue = false;
            }

            for(int i = 0; i < subGroup.size(); i++){
                subGroup.get(i).setCheckbox(newValue);
            }

            mOnGroupSelected.run(mDataset.get(finalPosition));
        });

        for (int i = 0; i < subGroup.size(); i++) {
            final OrdineAccettazioneGroupedInevasoDTO.Ordine ordine = subGroup.get(i);

            ordine.checkBoxCallback = new ArrayList<>();

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

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


            groupModelView.setVisibility(View.VISIBLE);

            if (i % 2 == 1) {
                groupModelView.setBackgroundColor(mContext.getResources().getColor(R.color.letturaFacilitataBG));
            } else {
                groupModelView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            }

            final CheckBox checkBox = groupModelView.findViewById(R.id.accettazione_main_list_group_item_container_checkBox);
            checkBox.setChecked(ordine.checkBox);

            ordine.checkBoxCallback.add(checkBox::setChecked);

            groupModelView.setOnClickListener(view -> {
                checkBox.toggle();
                ordine.checkBox = checkBox.isChecked();
                mOnGroupSelected.run(mDataset.get(finalPosition));
//                mCheckBoxCallback.onToggle(checkBox.isChecked());
            });

            TextView testataOrdTextView = groupModelView.findViewById(R.id.accettazione_main_list_group_item_container_testata_ord);
            String testataOrdString = String.format(mContext.getString(R.string.ord_acq_testata), String.valueOf(ordine.numero), UtilityDate.formatDate(ordine.getData(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN));
            testataOrdTextView.setText(Html.fromHtml(testataOrdString));

            LinearLayout clientLinearLayout = groupModelView.findViewById(R.id.accettazione_main_list_group_item_container_clienti_ord);
            List<OrdineAccettazioneGroupedInevasoDTO.Cliente> subGroupClienti = ordine.clienti;

            clientLinearLayout.removeAllViews();

            for (int k = 0; k < subGroupClienti.size(); k++) {


                View groupClienteModelViewPool = (View) sPoolClienti.acquire();
                if(groupClienteModelViewPool == null){
                    groupClienteModelViewPool = LayoutInflater.from(mContext)
                            .inflate(R.layout.accettazione_main_list_group_clienti, clientLinearLayout, false);
                }

                View groupClienteModelView = groupClienteModelViewPool;


                TextView clienteComm = groupClienteModelView.findViewById(R.id.accettazione_main_list_group_clienti_comm);
                String clienteText;
//                clienteText = subGroupClienti.get(k).codJcom + " - " + subGroupClienti.get(k).descrCom;
                clienteText = subGroupClienti.get(k).rifOrd;
                clienteComm.setText(clienteText);

                TextView dataCons = groupClienteModelView.findViewById(R.id.accettazione_main_list_group_clienti_datacons);
                if (subGroupClienti.get(k).getDataCons() != null) {
                    dataCons.setText(UtilityDate.formatDate(subGroupClienti.get(k).getDataCons(), UtilityDate.COMMONS_DATE_FORMATS.DMY_SLASH));
                } else {
                    dataCons.setText("");
                }

                clientLinearLayout.addView(groupClienteModelView);
            }

                holder.mLinearLayoutGroupItemContainer.addView(groupModelView);
        }


    }

    @Override
    public void onViewRecycled(ViewHolder holder){
        if(holder != null){
            for(int i = 0; i < holder.views.size(); i++){
                View groupModelView = holder.views.get(i);

                LinearLayout clientLinearLayout = groupModelView.findViewById(R.id.accettazione_main_list_group_item_container_clienti_ord);

                for(int k = 0; k < clientLinearLayout.getChildCount(); k++){
                    View cliente = clientLinearLayout.getChildAt(k);
                    ((ViewGroup) cliente.getParent()).removeView(cliente);

                    sPoolClienti.release(cliente);
                }

                ((ViewGroup) groupModelView.getParent()).removeView(groupModelView);
                sPool.release(groupModelView);
            }

            holder.views.clear();
        }

        super.onViewRecycled(holder);
    }

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


    public void setFilter(List<OrdineAccettazioneGroupedInevasoDTO> newDataset) {
        mDataset = new ArrayList<>();
        mDataset.addAll(newDataset);
        notifyDataSetChanged();
    }

}
