package it.integry.integrywmsnative.gest.prod_rientro_merce.order_list;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.annimon.stream.ComparatorCompat;
import com.annimon.stream.Stream;

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

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_cache.DataCache;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.databinding.FragmentProdRientroMerceOrderListBinding;
import it.integry.integrywmsnative.gest.prod_versamento_materiale.dto.OrdineLavorazioneDTO;
import it.integry.integrywmsnative.ui.ElevatedToolbar;
import it.integry.integrywmsnative.ui.SimpleDividerItemDecoration;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProdRientroMerceOrderListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProdRientroMerceOrderListFragment extends Fragment {

    private final ObservableArrayList<ProdRientroMerceOrderListModel> mOrdiniApertiMutableData = new ObservableArrayList<>();

    private FragmentProdRientroMerceOrderListBinding mBindings = null;

    private RunnableArgs<OrdineLavorazioneDTO> mOnItemSelectedRunnable;

    private ElevatedToolbar mToolbar;

    public ProdRientroMerceOrderListFragment() {
        // Required empty public constructor
    }

    public static ProdRientroMerceOrderListFragment newInstance(ElevatedToolbar elevatedToolbar) {
        Bundle args = new Bundle();

        args.putString("toolbarInstance", DataCache.addItem(elevatedToolbar));
        final ProdRientroMerceOrderListFragment prodRientroMerceOrderListFragment = new ProdRientroMerceOrderListFragment();
        prodRientroMerceOrderListFragment.setArguments(args);
        return prodRientroMerceOrderListFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        mToolbar = DataCache.retrieveItem(getArguments().getString("toolbarInstance"));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mBindings = DataBindingUtil.inflate(inflater, R.layout.fragment_prod_rientro_merce_order_list, container, false);

        mBindings.setLifecycleOwner(this);

        if(savedInstanceState == null) this.initRecyclerView();

        return mBindings.getRoot();
    }

    private void initRecyclerView() {
        SimpleDividerItemDecoration itemDecorator = new SimpleDividerItemDecoration(getActivity(), SimpleDividerItemDecoration.VERTICAL);
        itemDecorator.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.divider));
        this.mBindings.mainList.addItemDecoration(itemDecorator);


        ProdRientroMerceOrderListAdapter prodRientroMerceOrderListAdapter = new ProdRientroMerceOrderListAdapter(getActivity(), mOrdiniApertiMutableData)
                .setEmptyView(this.mBindings.emptyView)
                .setOnItemChecked(x -> {
                    if(mOnItemSelectedRunnable != null) mOnItemSelectedRunnable.run(x.getOriginalModel());
                });

        this.mBindings.mainList.setAdapter(prodRientroMerceOrderListAdapter);
        this.mBindings.mainList.setLayoutManager(new LinearLayoutManager(getActivity()));

        this.mToolbar.setRecyclerView(mBindings.mainList);
    }

    public void pushOrderList(List<OrdineLavorazioneDTO> orderList) {
        this.mOrdiniApertiMutableData.clear();
        this.mOrdiniApertiMutableData.addAll(convertDataModelToListModel(orderList));

    }


    private List<ProdRientroMerceOrderListModel> convertDataModelToListModel(List<OrdineLavorazioneDTO> dataList) {

        ComparatorCompat<OrdineLavorazioneDTO> comparator = ComparatorCompat
                .comparing(OrdineLavorazioneDTO::getCodJfas)
                .thenComparing(ComparatorCompat.comparing(ordineLavorazioneDTO -> ordineLavorazioneDTO.getDataOrd() != null ? ordineLavorazioneDTO.getDataOrd() : "zzzzzzzz")).reversed()
                .thenComparing(ComparatorCompat.comparing(OrdineLavorazioneDTO::getNumOrd));

        if(dataList == null) return new ArrayList<>();

        List<ProdRientroMerceOrderListModel> notHiddenElements = Stream.of(dataList)
                .sorted(comparator)
                .map(x -> {
                    ProdRientroMerceOrderListModel listModel = new ProdRientroMerceOrderListModel();

                    switch (x.getStatoEnum()) {
                        case IN_CORSO:
                            listModel.setIcon(ProdRientroMerceOrderListModel.StatoIconEnum.START);
                            break;
                        case PAUSA:
                            listModel.setIcon(ProdRientroMerceOrderListModel.StatoIconEnum.PAUSE);
                            break;
                        case PROGRAMMATO:
                        default:
                            listModel.setIcon(ProdRientroMerceOrderListModel.StatoIconEnum.SCHEDULED);
                            break;
                    }

                    listModel.setGroupTitle(x.getCodJfas());

                    if(!UtilityString.isNullOrEmpty(x.getRagSocAnag()))
                        listModel.setPreDescription("Provenienza: " + x.getRagSocAnag());

                    String testataOrdString = "N° " + x.getNumOrd();
                    listModel.setDescription(testataOrdString);

                    listModel.setSubDescription(x.getDescrizioneProd());

                    listModel.setRightDescription(x.getCodJcom() != null ? (x.getDescCommessa() + " (" + x.getCodJcom() + ")") : "");

                    try {
                        listModel.setRightSubDescription(UtilityDate.formatDate(x.getDataOrdD(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN));
                    } catch (Exception ex) {

                    }

                    listModel.setOriginalModel(x);

                    return listModel;
                })
                .toList();

        return notHiddenElements;
    }

    public ProdRientroMerceOrderListFragment setOnItemSelectedRunnable(RunnableArgs<OrdineLavorazioneDTO> onItemSelectedRunnable) {
        this.mOnItemSelectedRunnable = onItemSelectedRunnable;
        return this;
    }

    public RecyclerView getList() {
        return mBindings.mainList;
    }
}