package it.integry.integrywmsnative.gest.ordini_uscita_elenco;

import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.res.ResourcesCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.recyclerview.widget.LinearLayoutManager;

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

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

import javax.inject.Inject;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeCallbackDTO;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.data_cache.DataCache;
import it.integry.integrywmsnative.core.di.BindableBoolean;
import it.integry.integrywmsnative.core.expansion.BaseFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.interfaces.IFilterableFragment;
import it.integry.integrywmsnative.core.interfaces.IScrollableFragment;
import it.integry.integrywmsnative.core.interfaces.ISelectAllFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.model.secondary.GestioneEnum;
import it.integry.integrywmsnative.core.rest.model.OrdineUscitaInevasoDTO;
import it.integry.integrywmsnative.core.rest.model.SitArtOrdDTO;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.databinding.FragmentMainOrdiniUscitaBinding;
import it.integry.integrywmsnative.gest.ordini_uscita_elenco.dialogs.DialogVenditaFiltroAvanzatoView;
import it.integry.integrywmsnative.gest.ordini_uscita_elenco.dialogs.DialogVenditaFiltroAvanzatoViewModel;
import it.integry.integrywmsnative.gest.ordini_uscita_elenco.ui.OrdiniUscitaElencoAdapter;
import it.integry.integrywmsnative.gest.ordini_uscita_elenco.ui.OrdiniUscitaElencoListModel;
import it.integry.integrywmsnative.gest.spedizione.SpedizioneActivity;
import it.integry.integrywmsnative.gest.spedizione.dialogs.row_info.BaseDialogRowInfoView;
import it.integry.integrywmsnative.ui.ElevatedToolbar;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class OrdiniUscitaElencoFragment extends BaseFragment implements ITitledFragment, IScrollableFragment, ISelectAllFragment, IFilterableFragment, OrdiniUscitaElencoViewModel.Listener {

    public BindableBoolean fabVisible = new BindableBoolean(false);

    @Inject
    OrdiniUscitaElencoViewModel mViewModel;

    private FragmentMainOrdiniUscitaBinding mBindings = null;

    private final ObservableArrayList<OrdiniUscitaElencoListModel> mOrdiniInevasiMutableData = new ObservableArrayList<>();

    private GestioneEnum mCurrentGestioneOrd = null;
    private GestioneEnum mCurrentGestioneCol = null;
    private int mCurrentSegnoCol = 0;
    private Class<? extends BaseDialogRowInfoView> mDialogRowInfo;

    private ElevatedToolbar mToolbar;
    private final List<Runnable> mOnPreDestroyList = new ArrayList<>();

    private int barcodeScannerIstanceID = -1;


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

    public static OrdiniUscitaElencoFragment newInstance(GestioneEnum gestioneOrd, GestioneEnum gestioneCol, int segnoCol, Class<? extends BaseDialogRowInfoView> dialogRowInfo) {
        OrdiniUscitaElencoFragment fragment = new OrdiniUscitaElencoFragment();
        Bundle args = new Bundle();

        args.putString("gestioneOrd", gestioneOrd.getText());
        args.putString("gestioneCol", gestioneCol != null ? gestioneCol.getText() : null);
        args.putInt("segnoCol", segnoCol);

        String keyDialogRowInfo = DataCache.addItem(dialogRowInfo);
        args.putString("keyDialogRowInfo", keyDialogRowInfo);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCurrentGestioneOrd = GestioneEnum.fromString(getArguments().getString("gestioneOrd"));
        String gestioneCol = getArguments().getString("gestioneCol");
        mCurrentGestioneCol = gestioneCol != null ? GestioneEnum.fromString(gestioneCol) : null;
        mCurrentSegnoCol = getArguments().getInt("segnoCol");

        String keyDialogRowInfo = getArguments().getString("keyDialogRowInfo");
        mDialogRowInfo = DataCache.retrieveItem(keyDialogRowInfo);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mBindings = DataBindingUtil.inflate(inflater, R.layout.fragment_main_ordini_uscita, container, false);

        MainApplication.appComponent
                .prodOrdineLavorazioneElencoComponent()
                .create()
                .inject(this);

        mViewModel.setListener(this);

        mBindings.setLifecycleOwner(this);
        mBindings.setView(this);
        mBindings.setViewmodel(mViewModel);

        this.initRecyclerView();
        this.initBarcodeReader();

        return mBindings.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();

        String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep();
        mViewModel.init(codMdep, mCurrentGestioneOrd, mCurrentGestioneCol, mCurrentSegnoCol);
    }

    @Override
    public void onDestroy() {
        BarcodeManager.removeCallback(barcodeScannerIstanceID);

        for (Runnable onPreDestroy : mOnPreDestroyList) {
            onPreDestroy.run();
        }
        super.onDestroy();
    }

    private void initRecyclerView() {

        boolean canSelectMultipleOrdini = SettingsManager.iDB().isFlagSpedizioneCanSelectMultipleOrders();
        boolean canSelectMultipleClienti = SettingsManager.iDB().isFlagMultiClienteOrdV();

        this.mViewModel.getOrderList().observe(getViewLifecycleOwner(), v -> this.refreshList(null));

        OrdiniUscitaElencoAdapter ordiniUscitaElencoAdapter =
                new OrdiniUscitaElencoAdapter(getActivity(), mOrdiniInevasiMutableData)
                        .setOnGroupItemClicked(x -> {
                            if (!canSelectMultipleClienti) {
                                Stream.of(mOrdiniInevasiMutableData)
                                        .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x) && y.getSelectedObservable().get())
                                        .forEach(y -> y.getSelectedObservable().set(false));
                            }

                            boolean allSelected = Stream.of(mOrdiniInevasiMutableData)
                                    .filter(y -> y.getGroupTitle().equalsIgnoreCase(x))
                                    .allMatch(y -> y.getSelectedObservable().get());

                            Stream.of(mOrdiniInevasiMutableData)
                                    .filter(y -> y.getGroupTitle().equalsIgnoreCase(x))
                                    .forEach(y -> y.getSelectedObservable().set(!allSelected));
                        })
                        .setOnItemChecked(x -> {
                            if (!canSelectMultipleClienti && x.getSelectedObservable().get()) {
                                Stream.of(mOrdiniInevasiMutableData)
                                        .filter(y -> !y.getGroupTitle().equalsIgnoreCase(x.getGroupTitle()) && y.getSelectedObservable().get())
                                        .forEach(y -> y.getSelectedObservable().set(false));
                            }

                            fabVisible.set(Stream.of(mOrdiniInevasiMutableData)
                                    .anyMatch(y -> y.getSelectedObservable().get()));
                        });

        ordiniUscitaElencoAdapter
                .setEmptyView(this.mBindings.ordiniVenditaEmptyView);

        this.mBindings.venditaMainList.setAdapter(ordiniUscitaElencoAdapter);
        this.mBindings.venditaMainList.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (mToolbar != null)
            mToolbar.setRecyclerView(this.mBindings.venditaMainList);
    }

    private void initBarcodeReader() {
        barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO()
                .setOnScanSuccessfull(onScanSuccessful)
                .setOnScanFailed(ex -> UtilityExceptions.defaultException(getActivity(), ex, false)));

        BarcodeManager.enable();
    }

    private final RunnableArgs<BarcodeScanDTO> onScanSuccessful = data -> {
        BarcodeManager.disable();
        this.openProgress();

        this.mViewModel.processBarcodeDTO(data, () -> {
            BarcodeManager.enable();
            this.closeProgress();
        });
    };

    private void refreshList(List<OrdiniUscitaElencoDTO> filteredList) {
        List<OrdiniUscitaElencoDTO> tmpList = null;

        if(filteredList != null) {
            tmpList = filteredList;
        } else if (mAppliedFilterViewModel != null) {
            mAppliedFilterViewModel.init(mViewModel.getOrderList().getValue());
            mAppliedFilterViewModel.applyAllTests();
            tmpList = mAppliedFilterViewModel.getMutableFilteredOrderList().getValue();
        } else {
            tmpList = mViewModel.getOrderList().getValue();
        }

        this.mOrdiniInevasiMutableData.clear();
        this.mOrdiniInevasiMutableData.addAll(convertDataModelToListModel(tmpList));
    }

    private List<OrdiniUscitaElencoListModel> convertDataModelToListModel(List<OrdiniUscitaElencoDTO> dataList) {

        ComparatorCompat<OrdiniUscitaElencoDTO> comparator = ComparatorCompat
                .comparing(OrdiniUscitaElencoDTO::getRagSocOrd)
                .thenComparing(ComparatorCompat.comparing(x -> x.getDestinatario() != null ? x.getDestinatario() : "zzzzzzzzz"))
                .thenComparing(ComparatorCompat.comparing(OrdiniUscitaElencoDTO::getNumOrd));

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

                    if (x.isFlagEvaso()) {
                        listModel.setEtichettaColor(ResourcesCompat.getColor(getResources(), R.color.mainGreen, null));
                    } else if (x.isExistColloBoolean()) {
                        listModel.setEtichettaColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null));
                    } else {
                        listModel.setEtichettaColor(ResourcesCompat.getColor(getResources(), android.R.color.transparent, null));
                    }

                    listModel.setGroupTitle(x.getRagSocOrd());

                    String testataOrdString = String.format(getString(R.string.ord_ven_testata), String.valueOf(x.getNumOrd()), UtilityDate.formatDate(x.getDataOrdD(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN));
                    listModel.setDescription(testataOrdString);

                    listModel.setSubDescription(x.getRifOrd());

                    String testataDataConsString = String.format(getString(R.string.ord_ven_testata_data_cons), UtilityDate.formatDate(x.getDataConsD(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN));
                    listModel.setRightDescription(testataDataConsString);

                    listModel.setOriginalModel(x);

                    return listModel;
                })
                .toList();

        return notHiddenElements;
    }

    @Override
    public void onResume() {
        super.onResume();
        Stream.of(this.mOrdiniInevasiMutableData)
                .forEach(x -> x.getSelectedObservable().set(false));
    }

    @Override
    public void onCreateActionBar(AppCompatTextView titleText, Context context) {
        titleText.setText(context.getText(R.string.prod_ordine_lavorazione_title_fragment).toString());
    }


    public void dispatchOrders() {
        List<OrdiniUscitaElencoDTO> selectedOrders = Stream.of(this.mOrdiniInevasiMutableData)
                .filter(x -> x.getSelectedObservable().get())
                .map(OrdiniUscitaElencoListModel::getOriginalModel)
                .toList();

        this.mViewModel.loadPicking(selectedOrders);
    }

    @Override
    public void onOrderFiltered(List<OrdiniUscitaElencoDTO> filteredOrders) {
        refreshList(filteredOrders);
    }

    @Override
    public void onOrdersDispatched(List<OrdineUscitaInevasoDTO> orders, List<SitArtOrdDTO> sitArts, List<MtbColt> alreadyRegisteredMtbColts) {
        List<String> codMarts = Stream.of(sitArts)
                .distinctBy(SitArtOrdDTO::getCodMart)
                .map(SitArtOrdDTO::getCodMart)
                .toList();

        int alreadyRegisteredUL = alreadyRegisteredMtbColts.size();

        DialogSimpleMessageView.makeInfoDialog(getText(R.string.orders).toString(),
                Html.fromHtml(String.format(getActivity().getResources().getQuantityString(R.plurals.loaded_orders_message, orders.size()), orders.size())
                        + "<br />" +
                        "<b>" + codMarts.size() + "</b> " + getActivity().getResources().getQuantityString(R.plurals.available_articles, codMarts.size())
                        + "<br />" +
                        "<b>" + alreadyRegisteredUL + "</b> " + getActivity().getResources().getQuantityString(R.plurals.already_registered_lu, alreadyRegisteredUL)),
                null,
                () -> SpedizioneActivity.startActivity(getActivity(), sitArts, orders, alreadyRegisteredMtbColts, mCurrentGestioneCol, mCurrentSegnoCol, MtbColr.Causale.DEFAULT, mDialogRowInfo)
        ).show(getActivity().getSupportFragmentManager(), "tag");
    }

    @Override
    public void setScrollToolbar(ElevatedToolbar toolbar) {
        mToolbar = toolbar;
    }

    @Override
    public boolean isSelectAllButtonEnabled() {
        return SettingsManager.iDB().isFlagMultiClienteOrdV();
    }

    @Override
    public void onSelectAll() {
        boolean allSelected = Stream.of(mOrdiniInevasiMutableData)
                .allMatch(x -> x.getSelectedObservable().get());

        Stream.of(mOrdiniInevasiMutableData)
                .filter(x -> !x.getOriginalModel().isHidden())
                .forEach(x -> x.getSelectedObservable().set(!allSelected));
    }


    private DialogVenditaFiltroAvanzatoViewModel mAppliedFilterViewModel;

    @Override
    public void onFilterClick() {
        DialogVenditaFiltroAvanzatoView.make(
                getActivity(),
                this.mViewModel.getOrderList().getValue(),
                mAppliedFilterViewModel,

                filter -> {

                    mAppliedFilterViewModel = filter;
                    refreshList(null);

                }).show();
    }

    @Override
    public void addOnPreDestroy(Runnable onPreDestroy) {
        this.mOnPreDestroyList.add(onPreDestroy);
    }
}
