package it.integry.integrywmsnative.gest.spedizione.ui;

import android.content.Context;
import android.graphics.Color;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhukic.sectionedrecyclerview.SectionedRecyclerViewAdapter;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.expansion.OnListGeneralChangedCallback;
import it.integry.integrywmsnative.core.expansion.OnSingleClickListener;
import it.integry.integrywmsnative.core.expansion.RunnableArgsss;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityNumber;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.databinding.SpedizioneMainListGroupHeaderBinding;
import it.integry.integrywmsnative.databinding.SpedizioneMainListGroupItemBinding;
import it.integry.integrywmsnative.gest.spedizione.dialogs.row_info.BaseDialogRowInfoView;
import it.integry.integrywmsnative.gest.spedizione.model.PickingObjectDTO;

public class SpedizioneListAdapter extends SectionedRecyclerViewAdapter<SpedizioneListAdapter.SubheaderHolder, SpedizioneListAdapter.SingleItemViewHolder> {

    private final Context mContext;
    private final Class<? extends BaseDialogRowInfoView> mInfoDialogClassType;
    private final FragmentManager mFragmentManager;
    private final List<SpedizioneListModel> mDataset = new ArrayList<>();

    private RunnableArgsss<PickingObjectDTO, MtbColt, MtbColr> mOnItemClicked;

    static class SubheaderHolder extends RecyclerView.ViewHolder {

        SpedizioneMainListGroupHeaderBinding mBinding;

        SubheaderHolder(SpedizioneMainListGroupHeaderBinding binding) {
            super(binding.getRoot());
            this.mBinding = binding;
        }

    }

    static class SingleItemViewHolder extends RecyclerView.ViewHolder {

        SpedizioneMainListGroupItemBinding mBinding;

        SingleItemViewHolder(SpedizioneMainListGroupItemBinding binding) {
            super(binding.getRoot());
            this.mBinding = binding;
        }
    }


    public SpedizioneListAdapter(AppCompatActivity context, ObservableArrayList<SpedizioneListModel> mutableDataSet, Class<? extends BaseDialogRowInfoView> infoDialogClassType, FragmentManager fragmentManager) {
        this.mContext = context;
        this.mInfoDialogClassType = infoDialogClassType;
        this.mFragmentManager = fragmentManager;

        mutableDataSet.addOnListChangedCallback(new OnListGeneralChangedCallback() {
            @Override
            public void onChanged(ObservableList sender) {
                mDataset.clear();
                mDataset.addAll(sender);
                notifyDataSetChanged();
                notifyDataChanged();
            }
        });
    }

    public void setOnItemClicked(RunnableArgsss<PickingObjectDTO, MtbColt, MtbColr> onItemClicked) {
        this.mOnItemClicked = onItemClicked;
    }


    @Override
    public SubheaderHolder onCreateSubheaderViewHolder(ViewGroup parent, int viewType) {
        SpedizioneMainListGroupHeaderBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.spedizione_main_list__group_header, parent, false);
        return new SubheaderHolder(binding);
    }

    @Override
    public SingleItemViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) {
        SpedizioneMainListGroupItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.spedizione_main_list__group_item, parent, false);
        return new SingleItemViewHolder(binding);
    }


    @Override
    public void onBindSubheaderViewHolder(SubheaderHolder subheaderHolder, int nextItemPosition) {
        SpedizioneListModel pickingObjectDTO = this.mDataset.get(nextItemPosition);

        subheaderHolder.mBinding.spedizioneGroupTitle.setVisibility(UtilityString.isNullOrEmpty(pickingObjectDTO.getGroupTitle()) ? View.GONE : View.VISIBLE);
        subheaderHolder.mBinding.spedizioneGroupTitle.setText(pickingObjectDTO.getGroupTitle());
    }

    @Override
    public void onBindItemViewHolder(final SpedizioneListAdapter.SingleItemViewHolder holder, final int position) {
        SpedizioneListModel pickingObjectDTO = this.mDataset.get(position);

        if (pickingObjectDTO.getQtaEvasa().subtract(pickingObjectDTO.getQtaTot()).floatValue() >= 0) {
            holder.mBinding.getRoot().setBackgroundColor(mContext.getResources().getColor(R.color.green_500_with_alpha));
        } else if (pickingObjectDTO.getQtaEvasa().floatValue() > 0) {
            holder.mBinding.getRoot().setBackgroundColor(mContext.getResources().getColor(R.color.orange_600_with_alpha));
        } else if (position % 2 == 1) {
            holder.mBinding.getRoot().setBackgroundColor(Color.WHITE);
        } else {
            holder.mBinding.getRoot().setBackgroundColor(mContext.getResources().getColor(R.color.letturaFacilitataBG));
        }

        holder.mBinding.deactivatedOverBg.setVisibility(!pickingObjectDTO.isActive() ? View.VISIBLE : View.GONE);
        holder.mBinding.getRoot().setAlpha(!pickingObjectDTO.isActive() ? 0.8f : 1);
        holder.mBinding.badge1.setBackground(ResourcesCompat.getDrawable(mContext.getResources(), !pickingObjectDTO.isActive() ? R.drawable.badge_gray_round_corner : R.drawable.badge1_round_corner, null));
        holder.mBinding.qtaEvasa.setTextColor(ResourcesCompat.getColor(mContext.getResources(), !pickingObjectDTO.isActive() ? R.color.gray_600 : R.color.green_700, null));

        holder.mBinding.descrizione.setText(pickingObjectDTO.getDescrizione());
        holder.mBinding.descrizione.setTextColor(pickingObjectDTO.isDescrizionePresente() ? Color.BLACK : Color.GRAY);


        holder.mBinding.badge1.setText(pickingObjectDTO.getBadge1());
        holder.mBinding.badge2.setText(pickingObjectDTO.getBadge2());
        holder.mBinding.badge2.setVisibility(UtilityString.isNullOrEmpty(pickingObjectDTO.getBadge2()) ? View.GONE : View.VISIBLE);


        holder.mBinding.subdescrizione1.setText(UtilityString.isNullOrEmpty(pickingObjectDTO.getSubDescrizione1()) ? null : Html.fromHtml(pickingObjectDTO.getSubDescrizione1()));
        holder.mBinding.subdescrizione1.setVisibility(UtilityString.isNullOrEmpty(pickingObjectDTO.getSubDescrizione1()) ? View.GONE : View.VISIBLE);

        holder.mBinding.subdescrizione2.setText(UtilityString.isNullOrEmpty(pickingObjectDTO.getSubDescrizione2()) ? null : Html.fromHtml(pickingObjectDTO.getSubDescrizione2()));
        holder.mBinding.subdescrizione2.setVisibility(UtilityString.isNullOrEmpty(pickingObjectDTO.getSubDescrizione2()) ? View.GONE : View.VISIBLE);

        holder.mBinding.qtaEvasa.setText(UtilityNumber.decimalToString(pickingObjectDTO.getQtaEvasa()));
        holder.mBinding.qtaTot.setText(UtilityNumber.decimalToString(pickingObjectDTO.getQtaTot()));

        holder.mBinding.untMis.setText(pickingObjectDTO.getUntMis());
        holder.mBinding.untMis.setVisibility(UtilityString.isNullOrEmpty(pickingObjectDTO.getUntMis()) ? View.GONE : View.VISIBLE);

        if (mInfoDialogClassType != null) {
            holder.mBinding.infoRow.setVisibility(View.VISIBLE);
            holder.mBinding.infoRow.setOnClickListener(new OnSingleClickListener() {
                @Override
                public void onSingleClick(View v) {
                    openInfoDialog(pickingObjectDTO);
                }
            });
        }

        holder.mBinding.getRoot().setOnClickListener(v -> {
            if (this.mOnItemClicked != null)
                this.mOnItemClicked.run(pickingObjectDTO.getOriginalModel(), pickingObjectDTO.getSourceMtbColt(), pickingObjectDTO.getSourceMtbColr());
        });
    }


    @Override
    public boolean onPlaceSubheaderBetweenItems(int position) {

        if (getItemSize() == 1) return true;
        else if (getItemSize() > 1) {
            SpedizioneListModel compare1 = this.mDataset.get(position);
            SpedizioneListModel compare2 = this.mDataset.get(position + 1);

            if (UtilityString.equalsIgnoreCase(compare1.getGroupTitle(), compare2.getGroupTitle())) {
                return false;
            }
        }

        return true;
    }

    @Override
    public int getItemSize() {
        return mDataset.size();
    }


    private void openInfoDialog(SpedizioneListModel item) {
        try {
            Constructor<?> cons = Class.forName(mInfoDialogClassType.getName()).getConstructors()[0];
            BaseDialogRowInfoView object = (BaseDialogRowInfoView) cons.newInstance(item, (Runnable) () -> {

            }, (Runnable) () -> {

            });
            object.show(mFragmentManager, "tag");

        } catch (Exception e) {
            UtilityExceptions.defaultException(this.mContext, e);
        }

    }

}
