package it.integry.integrywmsnative.gest.spedizione;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.SpannableString;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.annimon.stream.Stream;
import com.tfb.fbtoast.FBToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.barcode_base_android_library.model.BarcodeType;
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.class_router.BaseCustomConfiguration;
import it.integry.integrywmsnative.core.class_router.ClassRouter;
import it.integry.integrywmsnative.core.class_router.interfaces.ICustomConfiguration;
import it.integry.integrywmsnative.core.data_cache.DataCache;
import it.integry.integrywmsnative.core.di.BindableBoolean;
import it.integry.integrywmsnative.core.expansion.AtomicBigDecimal;
import it.integry.integrywmsnative.core.expansion.BaseActivity;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.expansion.RunnableArgss;
import it.integry.integrywmsnative.core.expansion.RunnableArgsss;
import it.integry.integrywmsnative.core.model.MtbAart;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.model.MtbDepoPosizione;
import it.integry.integrywmsnative.core.model.MtbPartitaMag;
import it.integry.integrywmsnative.core.model.MtbTCol;
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.UtilityBigDecimal;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityResources;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.core.utility.UtilityToast;
import it.integry.integrywmsnative.databinding.ActivitySpedizioneBinding;
import it.integry.integrywmsnative.gest.lista_bancali.ListaBancaliActivity;
import it.integry.integrywmsnative.gest.spedizione.dialogs.print_sscc_list.DialogPrintOrderSSCCListView;
import it.integry.integrywmsnative.gest.spedizione.dialogs.row_info.BaseDialogRowInfoView;
import it.integry.integrywmsnative.gest.spedizione.exceptions.InvalidPesoKGException;
import it.integry.integrywmsnative.gest.spedizione.model.PickedQuantityDTO;
import it.integry.integrywmsnative.gest.spedizione.model.PickingObjectDTO;
import it.integry.integrywmsnative.gest.spedizione.model.PrintOrderCloseDTO;
import it.integry.integrywmsnative.gest.spedizione.ui.SpedizioneListAdapter;
import it.integry.integrywmsnative.gest.spedizione.ui.SpedizioneListModel;
import it.integry.integrywmsnative.view.bottom_sheet__lu_content.BottomSheetFragmentLUContentView;
import it.integry.integrywmsnative.view.bottom_sheet__lu_content.BottomSheetFragmentLUContentViewModel;
import it.integry.integrywmsnative.view.dialogs.DialogConsts;
import it.integry.integrywmsnative.view.dialogs.ask_position_of_lu.DialogAskPositionOfLUView;
import it.integry.integrywmsnative.view.dialogs.ask_should_print.DialogAskShouldPrint;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleInputHelper;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;
import it.integry.integrywmsnative.view.dialogs.choose_art_from_lista_arts.DialogChooseArtFromListaArtsView;
import it.integry.integrywmsnative.view.dialogs.choose_arts_from_lista_arts.DialogChooseArtsFromMtbAartListView;
import it.integry.integrywmsnative.view.dialogs.choose_batch_lot.DialogChooseBatchLotView;
import it.integry.integrywmsnative.view.dialogs.info_aggiuntive_lu.DialogInfoAggiuntiveLU;
import it.integry.integrywmsnative.view.dialogs.input_peso_lu.DialogInputPesoLUView;
import it.integry.integrywmsnative.view.dialogs.input_quantity_v2.DialogInputQuantityV2DTO;
import it.integry.integrywmsnative.view.dialogs.input_quantity_v2.DialogInputQuantityV2View;
import it.integry.integrywmsnative.view.dialogs.scan_art.DialogScanArtView;
import it.integry.integrywmsnative.view.dialogs.yes_no.DialogYesNoView;

public class SpedizioneActivity extends BaseActivity implements SpedizioneViewModel.Listener, BottomSheetFragmentLUContentViewModel.Listener, BottomSheetFragmentLUContentView.Listener {

    private ActivitySpedizioneBinding mBindings;

    @Inject
    SpedizioneViewModel mViewmodel;

    @Inject
    DialogInputQuantityV2View mDialogInputQuantityV2View;

    private BottomSheetFragmentLUContentViewModel mBottomSheetFragmentLUContentViewModel;

    private final ObservableArrayList<SpedizioneListModel> mSpedizioneMutableData = new ObservableArrayList<>();


    public BindableBoolean addExtraItemsEnabled = new BindableBoolean(false);
    public BindableBoolean noItemsToPick = new BindableBoolean(false);
    public BindableBoolean noLUPresent = new BindableBoolean(true);
    public BindableBoolean bottomSheetEnabled = new BindableBoolean(false);
    public BindableBoolean closeOrderButtonEnabled = new BindableBoolean(false);

    private boolean mEnableFakeGiacenza;
    private boolean mFlagShowCodForn;
    private boolean mDivideByGrpMerc;
    private boolean mEnableQuantityReset;
    private int barcodeScannerIstanceID = -1;

    private ArrayList<SitArtOrdDTO> mSitArtOrd;
    private ArrayList<OrdineUscitaInevasoDTO> mTestateOrdini;
    private ArrayList<MtbColt> mColliRegistrati;
    private GestioneEnum mGestioneCol;
    private int mSegnoCol;
    private Integer mDefaultCausaleUL;
    private Class<? extends BaseDialogRowInfoView> mInfoDialogClassType;

    private boolean mShouldCloseActivity;

    private final int PICK_UL_REQUEST = 1;

    public static void startActivity(Context context,
                                     List<SitArtOrdDTO> ordini,
                                     List<OrdineUscitaInevasoDTO> selectedOrders,
                                     List<MtbColt> mtbColtList,
                                     GestioneEnum gestioneCol,
                                     int segnoCol,
                                     Integer defaultCausaleUL,
                                     Class<? extends BaseDialogRowInfoView> infoDialogClassType) {
        Intent myIntent = new Intent(context, SpedizioneActivity.class);

        String keyPickingList = DataCache.addItem(ordini);
        myIntent.putExtra("keyPickingList", keyPickingList);

        String keyTestateOrdini = DataCache.addItem(selectedOrders);
        myIntent.putExtra("keyTestateOrdini", keyTestateOrdini);

        String keyColliRegistrati = DataCache.addItem(mtbColtList);
        myIntent.putExtra("keyColliRegistrati", keyColliRegistrati);

        String keyGestioneCol = DataCache.addItem(gestioneCol);
        myIntent.putExtra("keyGestioneCol", keyGestioneCol);

        String keySegnoCol = DataCache.addItem(segnoCol);
        myIntent.putExtra("keySegnoCol", keySegnoCol);

        String keyDefaultCausaleUL = DataCache.addItem(defaultCausaleUL);
        myIntent.putExtra("keyDefaultCausaleCol", keyDefaultCausaleUL);

        String keyInfoDialogClassType = DataCache.addItem(infoDialogClassType);
        myIntent.putExtra("keyInfoDialogClassType", keyInfoDialogClassType);

        context.startActivity(myIntent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSitArtOrd = DataCache.retrieveItem(getIntent().getStringExtra("keyPickingList"));
        mTestateOrdini = DataCache.retrieveItem(getIntent().getStringExtra("keyTestateOrdini"));
        mColliRegistrati = DataCache.retrieveItem(getIntent().getStringExtra("keyColliRegistrati"));
        mGestioneCol = DataCache.retrieveItem(getIntent().getStringExtra("keyGestioneCol"));
        mSegnoCol = DataCache.retrieveItem(getIntent().getStringExtra("keySegnoCol"));
        mDefaultCausaleUL = DataCache.retrieveItem(getIntent().getStringExtra("keyDefaultCausaleCol"));
        mInfoDialogClassType = DataCache.retrieveItem(getIntent().getStringExtra("keyInfoDialogClassType"));

        mBindings = DataBindingUtil.setContentView(this, R.layout.activity_spedizione);

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

        mViewmodel.setListeners(this);

        setSupportActionBar(mBindings.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        ICustomConfiguration customConfiguration = ClassRouter.getInstance(ClassRouter.PATH.CUSTOM_CONFIGURATION);
        mFlagShowCodForn = customConfiguration != null ? customConfiguration.getConfig(BaseCustomConfiguration.Keys.FLAG_SHOW_COD_FORN_IN_SPEDIZIONE) : true;
        mDivideByGrpMerc = customConfiguration != null ? customConfiguration.getConfig(BaseCustomConfiguration.Keys.FLAG_SPEDIZIONE_GROUP_BY_GRP_MERC) : false;

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mEnableQuantityReset = sharedPreferences.getBoolean("picking_uscita_enable_quantity_reset", true);

        mBindings.setLifecycleOwner(this);
        mBindings.setSpedizioneView(this);

        mBottomSheetFragmentLUContentViewModel = mBindings.bottomSheetLuContent.getViewModelInstance();
        mBindings.bottomSheetLuContent.setListener(this);
        mBottomSheetFragmentLUContentViewModel.setListener(this);

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

        closeOrderButtonEnabled.set(SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()
                || SettingsManager.iDB().isFlagPrintPackingListOnOrderClose()
                || (this.isOrdTrasf() && !UtilityString.isNullOrEmpty(SettingsManager.iDB().getCodDtipOrdTrasfV()))
        );


        String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep();
        mEnableFakeGiacenza = SettingsManager.iDB().isFlagSpedizioneEnableFakeGiacenza();
        boolean enableCheckPartitaMag = SettingsManager.iDB().isEnableCheckPartitaMagCheckPickingV();
        boolean canOverflowOrderQuantity = SettingsManager.iDB().isFlagCanAddExtraQuantitySpedizione();
        boolean shouldAskPesoLU = SettingsManager.iDB().isFlagAskPesoColloSpedizione();
        boolean useQtaOrd = SettingsManager.iDB().isFlagSpedizioneUseQtaOrd();

        mViewmodel.init(
                codMdep,
                !mEnableFakeGiacenza,
                enableCheckPartitaMag,
                shouldAskPesoLU,
                canOverflowOrderQuantity,
                mSitArtOrd,
                mTestateOrdini,
                mColliRegistrati,
                mGestioneCol, mSegnoCol, mDefaultCausaleUL,
                mEnableQuantityReset,
                useQtaOrd);
    }


    private boolean isOrdTrasf() {

        return mTestateOrdini != null && !mTestateOrdini.isEmpty() && Stream.of(mTestateOrdini)
                .map(OrdineUscitaInevasoDTO::isOrdTrasf)
                .withoutNulls()
                .distinctBy(x -> x)
                .findFirst()
                .get();
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    public void onBackPressed() {

        if (this.mBindings.bottomSheetLuContent.isExpanded()) {
            this.mBindings.bottomSheetLuContent.collapse();
        } else if (!noLUPresent.get()) {
            this.mShouldCloseActivity = true;
            BarcodeManager.removeCallback(barcodeScannerIstanceID);
            this.mViewmodel.requestCloseLU(true);
        } else {
            BarcodeManager.removeCallback(barcodeScannerIstanceID);
            super.onBackPressed();
        }
    }

    private void initVars() {
        this.noLUPresent.addOnPropertyChangedCallback(() -> {
            this.bottomSheetEnabled.set(!this.noLUPresent.get());
        });
    }

    private void initBarcodeReader() {
        barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO()
                .setOnScanSuccessful(onScanSuccessful)
                .setOnScanFailed(this::onError));

        BarcodeManager.enable();
    }

    private void initRecyclerView() {
        this.mViewmodel.getPickingList().observe(this, updatedData -> {
            this.mSpedizioneMutableData.clear();
            this.mSpedizioneMutableData.addAll(convertDataModelToListModel(updatedData));
            this.noItemsToPick.set(!isThereAnyItemToPick(updatedData));
        });

        SpedizioneListAdapter spedizioneListAdapter = new SpedizioneListAdapter(this, mSpedizioneMutableData, mInfoDialogClassType, getSupportFragmentManager());
        this.mBindings.spedizionePickingList.setAdapter(spedizioneListAdapter);
        this.mBindings.spedizionePickingList.setLayoutManager(new LinearLayoutManager(this));

        spedizioneListAdapter.setOnItemClicked((clickedItem, refMtbColt, refMtbColr) -> {
            if (!noLUPresent.get() &&
                    ((SettingsManager.iDB().isFlagSpedizioneEnableManualPick() &&
                            clickedItem.getSitArtOrdDTO().isFlagEnablePickManuale()) ||
                            clickedItem.getTempPickData() != null)) {
                this.mViewmodel.dispatchOrdineRow(clickedItem, refMtbColt, refMtbColr,
                        SettingsManager.iDB().isFlagSpedizioneEnableManualPick() && clickedItem.getSitArtOrdDTO().isFlagEnablePickManuale());
            }
        });
    }


    private List<SpedizioneListModel> convertDataModelToListModel(List<PickingObjectDTO> dataList) {

        List<PickingObjectDTO> tmpList = Stream.of(dataList)
                .filter(x -> !x.isHidden() && UtilityBigDecimal.greaterThan(x.getSitArtOrdDTO().getQtaOrd(), BigDecimal.ZERO))
                .toList();

        List<SpedizioneListModel> spedizioneListModels = new ArrayList<>();

        List<SpedizioneListModel> sortedList = null;

        if (!mDivideByGrpMerc) {
            Stream.of(tmpList)
                    .forEach(x -> {
                        SpedizioneListModel spedizioneListModel = new SpedizioneListModel();

                        String badge1 = "";
                        if (mFlagShowCodForn) {
                            badge1 += !UtilityString.isNullOrEmpty(x.getSitArtOrdDTO().getCodAlis()) ? (x.getSitArtOrdDTO().getCodAlis() + " - ") : "";
                            badge1 += (!UtilityString.isNullOrEmpty(x.getSitArtOrdDTO().getCodArtFor()) ? x.getSitArtOrdDTO().getCodArtFor() : x.getMtbAart().getCodMart());
                        } else {
                            badge1 += x.getMtbAart().getCodMart();
                        }

                        spedizioneListModel.setBadge1(badge1);

                        if (UtilityString.isNullOrEmpty(x.getMtbAart().getDescrizioneEstesa())) {
                            spedizioneListModel.setDescrizione(getString(R.string.no_description));
                            spedizioneListModel.setDescrizionePresente(false);
                        } else {
                            spedizioneListModel.setDescrizione(x.getMtbAart().getDescrizioneEstesa());
                            spedizioneListModel.setDescrizionePresente(true);
                        }


                        boolean anyLUPresent = x.getMtbColts() != null && x.getMtbColts().size() > 0;

                        spedizioneListModel.setActive(mEnableFakeGiacenza || anyLUPresent);


                        AtomicBigDecimal numCnfWithdrawRows = new AtomicBigDecimal();
                        AtomicBigDecimal qtaColWithdrawRows = new AtomicBigDecimal();

                        Stream.of(x.getWithdrawMtbColrs())
                                .forEach(row -> {
                                    numCnfWithdrawRows.addAndGet(row.getNumCnf());
                                    qtaColWithdrawRows.addAndGet(row.getQtaCol());
                                });

                        spedizioneListModel.setBadge2(x.getSitArtOrdDTO().getCodJcom());

                        if (!anyLUPresent) {
                            spedizioneListModel.setGroupTitle(!mEnableFakeGiacenza ? getString(R.string.picking_not_available) : "");

                            if (SettingsManager.iDB().isFlagForceAllToColli() || (x.getMtbAart() == null || !x.getMtbAart().isFlagQtaCnfFissaBoolean())) {
                                spedizioneListModel.setUntMis(UtilityResources.getString(R.string.unt_mis_col));
                                spedizioneListModel.setQtaTot(x.getSitArtOrdDTO().getNumCnfOrd());
                                spedizioneListModel.setQtaEvasa(numCnfWithdrawRows.getBigDecimalValue());
                            } else {
                                spedizioneListModel.setQtaTot(x.getSitArtOrdDTO().getQtaOrd());
                                spedizioneListModel.setQtaEvasa(qtaColWithdrawRows.getBigDecimalValue());
                                if (x.getMtbAart() != null)
                                    spedizioneListModel.setUntMis(x.getMtbAart().getUntMis());
                            }

                            BigDecimal qtaOmg = x.getSitArtOrdDTO().getQtaOmg();
                            if (qtaOmg != null && qtaOmg.compareTo(BigDecimal.ZERO) > 0) {
                                spedizioneListModel.setFreeQuantity(String.format(getString(R.string.ord_ven_qta_omaggio), qtaOmg.stripTrailingZeros().toPlainString(), spedizioneListModel.getUntMis()));
                            }

                            spedizioneListModel.setOriginalModel(x);
                            spedizioneListModels.add(spedizioneListModel);
                        } else {

                            BigDecimal qtaColOrdCounter = x.getSitArtOrdDTO().getQtaOrd();
                            BigDecimal numCnfOrdCounter = x.getSitArtOrdDTO().getNumCnfOrd();

                            for (MtbColt mtbColtToPick : x.getMtbColts()) {

                                if (UtilityBigDecimal.equalsTo(qtaColOrdCounter, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(qtaColOrdCounter, BigDecimal.ZERO))
                                    break;

                                if (UtilityBigDecimal.equalsTo(numCnfOrdCounter, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(numCnfOrdCounter, BigDecimal.ZERO))
                                    break;

                                SpedizioneListModel cloneModel = (SpedizioneListModel) spedizioneListModel.clone();

                                cloneModel.setGroupTitle(String.format("%s: %s", getString(R.string.position_text), UtilityString.isNullOrEmpty(mtbColtToPick.getPosizione()) ? "N.A." : mtbColtToPick.getPosizione()));

                                MtbColr mtbColrToDispatch = mtbColtToPick.getMtbColr() != null && mtbColtToPick.getMtbColr().size() > 0 ? mtbColtToPick.getMtbColr().get(0) : null;
                                if (mtbColrToDispatch != null && !UtilityString.isNullOrEmpty(mtbColrToDispatch.getPartitaMag())) {
                                    cloneModel.setSubDescrizione1(String.format(getString(R.string.batch_lot_text), mtbColrToDispatch.getPartitaMag()));
                                    cloneModel.setBadge2(mtbColrToDispatch.getCodJcom());
                                }
                                cloneModel.setSourceMtbColr(mtbColrToDispatch);

                                cloneModel.setSubDescrizione2(String.format(getString(R.string.lu_number_data_text), mtbColtToPick.getNumCollo(), UtilityDate.formatDate(mtbColtToPick.getDataColloD(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN)));

                                if (SettingsManager.iDB().isFlagForceAllToColli() || (x.getMtbAart() == null || !x.getMtbAart().isFlagQtaCnfFissaBoolean())) {
                                    cloneModel.setUntMis(UtilityResources.getString(R.string.unt_mis_col));

                                    BigDecimal numCnfOrdToSubstract = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getNumCnf(), numCnfOrdCounter);

                                    BigDecimal qtaTot = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getNumCnf(), numCnfOrdCounter);
                                    if (UtilityBigDecimal.equalsTo(qtaTot, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(qtaTot, BigDecimal.ZERO))
                                        continue;
                                    cloneModel.setQtaTot(qtaTot);

                                    numCnfOrdCounter = numCnfOrdCounter.subtract(numCnfOrdToSubstract);

                                    BigDecimal qtaEvasa = Stream.of(x.getWithdrawMtbColrs())
                                            .filter(y -> y.getRefMtbColr() != null &&/*
                                                    y.getRefMtbColr().getNumCollo().equals(mtbColrToDispatch.getNumCollo()) &&
                                                    y.getRefMtbColr().getDataColloD().equals(mtbColrToDispatch.getDataColloD()) &&
                                                    y.getRefMtbColr().getSerCollo().equals(mtbColrToDispatch.getSerCollo()) &&
                                                    y.getRefMtbColr().getGestioneEnum().equals(mtbColrToDispatch.getGestioneEnum()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodMart(), mtbColrToDispatch.getCodMart()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodTagl(), mtbColrToDispatch.getCodTagl()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodCol(), mtbColrToDispatch.getCodCol())*/
                                                    y.getRefMtbColr().equals(mtbColrToDispatch))
                                            .map(MtbColr::getNumCnf)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                                    cloneModel.setQtaEvasa(qtaEvasa);

                                } else {

                                    BigDecimal qtaOrdToSubstract = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getQtaCol(), qtaColOrdCounter);

                                    BigDecimal qtaTot = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getQtaCol(), qtaColOrdCounter);
                                    if (UtilityBigDecimal.equalsTo(qtaTot, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(qtaTot, BigDecimal.ZERO))
                                        continue;
                                    cloneModel.setQtaTot(qtaTot);
                                    qtaColOrdCounter = qtaColOrdCounter.subtract(qtaOrdToSubstract);

                                    BigDecimal qtaEvasa = Stream.of(x.getWithdrawMtbColrs())
                                            .filter(y -> y.getRefMtbColr() != null &&
                                                            y.getRefMtbColr().getId() == mtbColrToDispatch.getId()
                                                    /*
                                                    y.getRefMtbColr().getNumCollo().equals(mtbColrToDispatch.getNumCollo()) &&
                                                    y.getRefMtbColr().getDataColloD().equals(mtbColrToDispatch.getDataColloD()) &&
                                                    y.getRefMtbColr().getSerCollo().equals(mtbColrToDispatch.getSerCollo()) &&
                                                    y.getRefMtbColr().getGestioneEnum().equals(mtbColrToDispatch.getGestioneEnum()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodMart(), mtbColrToDispatch.getCodMart()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodTagl(), mtbColrToDispatch.getCodTagl()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodCol(), mtbColrToDispatch.getCodCol())*/)
                                            .map(MtbColr::getQtaCol)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                                    cloneModel.setQtaEvasa(qtaEvasa);
                                    if (x.getMtbAart() != null)
                                        cloneModel.setUntMis(x.getMtbAart().getUntMis());
                                }

                                cloneModel.setOriginalModel(x);
                                cloneModel.setSourceMtbColt(mtbColtToPick);
                                spedizioneListModels.add(cloneModel);
                            }
                        }
                    });


            sortedList = Stream.of(spedizioneListModels)
                    .filter(x -> x.isActive() && (x.getSourceMtbColt() != null && !UtilityString.isNullOrEmpty(x.getSourceMtbColt().getPosizione())))
                    .sortBy(x -> x.getSourceMtbColt().getPosizione())
                    .toList();

            sortedList.addAll(
                    Stream.of(spedizioneListModels)
                            .filter(x -> x.isActive() && x.getSourceMtbColt() == null || (x.getSourceMtbColt() != null && UtilityString.isNullOrEmpty(x.getSourceMtbColt().getPosizione())))
                            .toList()
            );

            sortedList.addAll(
                    Stream.of(spedizioneListModels)
                            .filter(x -> !x.isActive())
                            .toList()
            );
        } else {
            Stream.of(tmpList)
                    .forEach(x -> {
                        SpedizioneListModel spedizioneListModel = new SpedizioneListModel();

                        String badge1 = "";
                        if (mFlagShowCodForn) {
                            badge1 += !UtilityString.isNullOrEmpty(x.getSitArtOrdDTO().getCodAlis()) ? (x.getSitArtOrdDTO().getCodAlis() + " - ") : "";
                            badge1 += (!UtilityString.isNullOrEmpty(x.getSitArtOrdDTO().getCodArtFor()) ? x.getSitArtOrdDTO().getCodArtFor() : x.getMtbAart().getCodMart());
                        } else {
                            badge1 += x.getMtbAart().getCodMart();
                        }

                        spedizioneListModel.setBadge1(badge1);

                        if (UtilityString.isNullOrEmpty(x.getMtbAart().getDescrizioneEstesa())) {
                            spedizioneListModel.setDescrizione(getString(R.string.no_description));
                            spedizioneListModel.setDescrizionePresente(false);
                        } else {
                            spedizioneListModel.setDescrizione(x.getMtbAart().getDescrizioneEstesa());
                            spedizioneListModel.setDescrizionePresente(true);
                        }


                        boolean anyLUPresent = x.getMtbColts() != null && x.getMtbColts().size() > 0;

                        spedizioneListModel.setActive(mEnableFakeGiacenza || anyLUPresent);


                        AtomicBigDecimal numCnfWithdrawRows = new AtomicBigDecimal();
                        AtomicBigDecimal qtaColWithdrawRows = new AtomicBigDecimal();

                        Stream.of(x.getWithdrawMtbColrs())
                                .forEach(row -> {
                                    numCnfWithdrawRows.addAndGet(row.getNumCnf());
                                    qtaColWithdrawRows.addAndGet(row.getQtaCol());
                                });


                        String groupTitle = String.format("%s - %s", x.getSitArtOrdDTO().getDescrizioneMgrp(), x.getSitArtOrdDTO().getDescrizioneMsgr());

                        if (!UtilityString.isNullOrEmpty(x.getSitArtOrdDTO().getDescrizioneMsfa())) {
                            groupTitle += " - " + x.getSitArtOrdDTO().getDescrizioneMsfa();
                        }

                        spedizioneListModel.setGroupTitle(groupTitle);

                        if (!anyLUPresent) {
                            spedizioneListModel.setBadge2(x.getSitArtOrdDTO().getCodJcom());

                            if (SettingsManager.iDB().isFlagForceAllToColli() || (x.getMtbAart() == null || !x.getMtbAart().isFlagQtaCnfFissaBoolean())) {
                                spedizioneListModel.setUntMis(UtilityResources.getString(R.string.unt_mis_col));
                                spedizioneListModel.setQtaTot(x.getSitArtOrdDTO().getNumCnfOrd());
                                spedizioneListModel.setQtaEvasa(numCnfWithdrawRows.getBigDecimalValue());
                            } else {
                                spedizioneListModel.setQtaTot(x.getSitArtOrdDTO().getQtaOrd());
                                spedizioneListModel.setQtaEvasa(qtaColWithdrawRows.getBigDecimalValue());
                                if (x.getMtbAart() != null)
                                    spedizioneListModel.setUntMis(x.getMtbAart().getUntMis());
                            }

                            spedizioneListModel.setOriginalModel(x);
                            spedizioneListModels.add(spedizioneListModel);
                        } else {

                            BigDecimal qtaColOrdCounter = x.getSitArtOrdDTO().getQtaOrd();
                            BigDecimal numCnfOrdCounter = x.getSitArtOrdDTO().getNumCnfOrd();


                            for (MtbColt mtbColtToPick : x.getMtbColts()) {

                                if (UtilityBigDecimal.equalsTo(qtaColOrdCounter, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(qtaColOrdCounter, BigDecimal.ZERO))
                                    break;

                                if (UtilityBigDecimal.equalsTo(numCnfOrdCounter, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(numCnfOrdCounter, BigDecimal.ZERO))
                                    break;

                                SpedizioneListModel cloneModel = (SpedizioneListModel) spedizioneListModel.clone();


                                MtbColr mtbColrToDispatch = mtbColtToPick.getMtbColr() != null && mtbColtToPick.getMtbColr().size() > 0 ? mtbColtToPick.getMtbColr().get(0) : null;
                                if (mtbColrToDispatch != null && !UtilityString.isNullOrEmpty(mtbColrToDispatch.getPartitaMag())) {
                                    cloneModel.setSubDescrizione1(String.format(getString(R.string.batch_lot_text), mtbColrToDispatch.getPartitaMag()));
                                    cloneModel.setBadge2(mtbColrToDispatch.getCodJcom());
                                }
                                cloneModel.setSourceMtbColr(mtbColrToDispatch);

                                cloneModel.setSubDescrizione2(String.format(getString(R.string.lu_number_data_text), mtbColtToPick.getNumCollo(), UtilityDate.formatDate(mtbColtToPick.getDataColloD(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN)));

                                if (SettingsManager.iDB().isFlagForceAllToColli() || (x.getMtbAart() == null || !x.getMtbAart().isFlagQtaCnfFissaBoolean())) {
                                    cloneModel.setUntMis(UtilityResources.getString(R.string.unt_mis_col));

                                    BigDecimal numCnfOrdToSubstract = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getNumCnf(), numCnfOrdCounter);

                                    BigDecimal qtaTot = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getNumCnf(), numCnfOrdCounter);
                                    if (UtilityBigDecimal.equalsTo(qtaTot, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(qtaTot, BigDecimal.ZERO))
                                        continue;
                                    cloneModel.setQtaTot(qtaTot);

                                    numCnfOrdCounter = numCnfOrdCounter.subtract(numCnfOrdToSubstract);

                                    BigDecimal qtaEvasa = Stream.of(x.getWithdrawMtbColrs())
                                            .filter(y -> y.getRefMtbColr() != null &&
                                                    y.getRefMtbColr().getId() == mtbColrToDispatch.getId() /*
                                                    y.getRefMtbColr().getNumCollo().equals(mtbColrToDispatch.getNumCollo()) &&
                                                    y.getRefMtbColr().getDataColloD().equals(mtbColrToDispatch.getDataColloD()) &&
                                                    y.getRefMtbColr().getSerCollo().equals(mtbColrToDispatch.getSerCollo()) &&
                                                    y.getRefMtbColr().getGestioneEnum().equals(mtbColrToDispatch.getGestioneEnum()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodMart(), mtbColrToDispatch.getCodMart()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodTagl(), mtbColrToDispatch.getCodTagl()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodCol(), mtbColrToDispatch.getCodCol())*/)
                                            .map(MtbColr::getNumCnf)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                                    cloneModel.setQtaEvasa(qtaEvasa);
                                } else {
                                    BigDecimal qtaOrdToSubstract = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getQtaCol(), qtaColOrdCounter);

                                    BigDecimal qtaTot = UtilityBigDecimal.getLowerBetween(mtbColrToDispatch.getQtaCol(), qtaColOrdCounter);
                                    if (UtilityBigDecimal.equalsTo(qtaTot, BigDecimal.ZERO) || UtilityBigDecimal.lowerThan(qtaTot, BigDecimal.ZERO))
                                        continue;
                                    cloneModel.setQtaTot(qtaTot);
                                    qtaColOrdCounter = qtaColOrdCounter.subtract(qtaOrdToSubstract);

                                    BigDecimal qtaEvasa = Stream.of(x.getWithdrawMtbColrs())
                                            .filter(y -> y.getRefMtbColr() != null &&
                                                    y.getRefMtbColr().getId() == mtbColrToDispatch.getId() /*
                                                    y.getRefMtbColr().getNumCollo().equals(mtbColrToDispatch.getNumCollo()) &&
                                                    y.getRefMtbColr().getDataColloD().equals(mtbColrToDispatch.getDataColloD()) &&
                                                    y.getRefMtbColr().getSerCollo().equals(mtbColrToDispatch.getSerCollo()) &&
                                                    y.getRefMtbColr().getGestioneEnum().equals(mtbColrToDispatch.getGestioneEnum()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodMart(), mtbColrToDispatch.getCodMart()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodTagl(), mtbColrToDispatch.getCodTagl()) &&
                                                    UtilityString.equalsIgnoreCase(y.getRefMtbColr().getCodCol(), mtbColrToDispatch.getCodCol())*/)
                                            .map(MtbColr::getQtaCol)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                                    cloneModel.setQtaEvasa(qtaEvasa);
                                    if (x.getMtbAart() != null)
                                        cloneModel.setUntMis(x.getMtbAart().getUntMis());
                                }

                                cloneModel.setOriginalModel(x);
                                cloneModel.setSourceMtbColt(mtbColtToPick);
                                spedizioneListModels.add(cloneModel);
                            }
                        }
                    });


            sortedList = Stream.of(spedizioneListModels)
                    .filter(SpedizioneListModel::isActive)
                    .sortBy(x -> x.getOriginalModel().getSitArtOrdDTO().getCodMgrp() + " - " + x.getOriginalModel().getSitArtOrdDTO().getCodMsgr())
                    .toList();


            sortedList.addAll(
                    Stream.of(spedizioneListModels)
                            .filter(x -> !x.isActive())
                            .toList()
            );
        }

        return sortedList;
    }

    private boolean isThereAnyItemToPick(List<PickingObjectDTO> dataList) {
        return Stream.of(dataList)
                .anyMatch(x -> !x.isHidden());
    }


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

        this.mViewmodel.processBarcodeDTO(data, () -> {
            this.onLoadingEnded();
        });
    };

    public void addExtraItem() {
        DialogScanArtView
                .newInstance(!mEnableFakeGiacenza, (status, mtbAart, ean128Model, mtbColr) -> {
                    if (status == DialogConsts.Results.YES) {
                        this.mViewmodel.dispatchExtraItem(mtbAart, ean128Model, mtbColr);
                    }
                })
                .show(getSupportFragmentManager(), "tag");
    }

    public void startManualSearch() {
        BarcodeManager.disable();
        DialogSimpleInputHelper.makeInputDialog(this, "Inserisci il codice a barre", codice -> {

            this.onScanSuccessful.run(new BarcodeScanDTO().setStringValue(codice).setType(BarcodeType.CODE128));
            BarcodeManager.enable();

        }, BarcodeManager::enable).show();
    }

    public void removeListFilter() {
        this.mViewmodel.resetMatchedRows();
    }


    public void createNewUL() {
        this.mBindings.spedizioneFab.close(true);

        this.onLoadingStarted();

        this.mViewmodel.createNewLU(null, null, () -> {
            this.onLoadingEnded();
        });
    }

    public void showCreatedUL() {
        this.mBindings.spedizioneFab.close(true);

        ArrayList<MtbColt> createdMtbColts = this.mViewmodel.getCreatedMtbColts();

        Intent myIntent = ListaBancaliActivity.createIntent(this, createdMtbColts, true, false);
        this.startActivityForResult(myIntent, PICK_UL_REQUEST);
    }


    public void closeOrder() {
        this.mBindings.spedizioneFab.close(true);

        this.mViewmodel.closeOrder();
    }

    @Override
    public void onLUOpened(MtbColt mtbColt) {
        this.addExtraItemsEnabled.set(SettingsManager.iDB().isFlagCanAddExtraItemSpedizione());
        noLUPresent.set(false);
        closeOrderButtonEnabled.set(false);

        FBToast.successToast(this, getResources().getString(R.string.data_saved), FBToast.LENGTH_SHORT);

        this.mBottomSheetFragmentLUContentViewModel.setMtbColt(mtbColt);
    }

    @Override
    public void onLUClosed() {
        this.addExtraItemsEnabled.set(false);
        noLUPresent.set(true);
        this.mBottomSheetFragmentLUContentViewModel.setMtbColt(null);
        closeOrderButtonEnabled.set(SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose() || SettingsManager.iDB().isFlagPrintPackingListOnOrderClose());

        if (this.mShouldCloseActivity) super.onBackPressed();
    }

    @Override
    public void onLUPesoRequired(String codTcol, BigDecimal netWeightKG, BigDecimal grossWeightKG, RunnableArgsss<String, BigDecimal, BigDecimal> onComplete) {
        DialogInputPesoLUView.newInstance(null, new BigDecimal(50), new BigDecimal(55), (newCodTcol, newNetWeight, newGrossWeight) -> {
                    onComplete.run(newCodTcol, netWeightKG, grossWeightKG);
                })
                .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onLUSuccessullyPrinted() {
        Resources res = getResources();
        String errorMessage = res.getText(R.string.alert_print_completed_message).toString();
        DialogSimpleMessageView
                .makeSuccessDialog(res.getText(R.string.completed).toString(), new SpannableString(errorMessage), null, null)
                .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onLUPrintRequest(RunnableArgs<Boolean> onComplete) {
        DialogAskShouldPrint.make(this, "Packing List", onComplete).show();
    }

    @Override
    public void onLUPrintError(Exception ex, Runnable onComplete) {
        this.onLoadingEnded();
        DialogSimpleMessageView.makeErrorDialog(
                        new SpannableString(ex.getMessage()),
                        null,
                        null,
                        R.string.button_ignore_print,
                        onComplete)
                .show(getSupportFragmentManager(), "tag");
        ;
    }

    @Override
    public void onFilterApplied(String newValue) {
        this.mBindings.filteredArtsInListExpandableLayout.expand(true);
        this.mBindings.descriptionFilterText.setText(!UtilityString.isNullOrEmpty(newValue) ? newValue : "");
    }

    @Override
    public void onFilterRemoved() {
        this.mBindings.filteredArtsInListExpandableLayout.collapse(true);
        this.mBindings.descriptionFilterText.setText("");
    }

    @Override
    public void onMtbColrDeleteRequest(RunnableArgs<Boolean> onComplete) {
        String text = getResources().getString(R.string.alert_delete_mtb_colr);
        DialogSimpleMessageView.makeWarningDialog(new SpannableString(text),
                        null,
                        () -> onComplete.run(true),
                        () -> onComplete.run(false)
                )
                .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onError(Exception ex) {
        this.onLoadingEnded();

        if (ex instanceof InvalidPesoKGException) {
            UtilityToast.showToast(ex.getMessage());
        } else {
            UtilityExceptions.defaultException(this, ex);
        }

        BarcodeManager.enable();
    }

    @Override
    public void onFullItemDispatched(PickingObjectDTO pickingObjectDTO,
                                     MtbAart mtbAart,
                                     BigDecimal initialNumCnf,
                                     BigDecimal initialQtaCnf,
                                     BigDecimal initialQtaTot,
                                     BigDecimal totalQtaOrd,
                                     BigDecimal totalNumCnfOrd,
                                     BigDecimal qtaCnfOrd,
                                     BigDecimal totalQtaToBeTaken,
                                     BigDecimal totalNumCnfToBeTaken,
                                     BigDecimal qtaCnfToBeTaken,
                                     BigDecimal totalQtaAvailable,
                                     BigDecimal totalNumCnfAvailable,
                                     BigDecimal qtaCnfAvailable,
                                     String partitaMag,
                                     Date dataScad,
                                     boolean canOverflowOrderQuantity,
                                     boolean canPartitaMagBeChanged,
                                     RunnableArgss<PickedQuantityDTO, Boolean> onComplete) {

        DialogInputQuantityV2DTO dialogInputQuantityV2DTO = new DialogInputQuantityV2DTO()
                .setMtbAart(mtbAart)
                .setInitialNumCnf(initialNumCnf)
                .setInitialQtaCnf(initialQtaCnf)
                .setInitialQtaTot(initialQtaTot)
                .setTotalQtaOrd(totalQtaOrd)
                .setTotalNumCnfOrd(totalNumCnfOrd)
                .setQtaCnfOrd(qtaCnfOrd)
                .setTotalQtaToBeTaken(totalQtaToBeTaken)
                .setTotalNumCnfToBeTaken(totalNumCnfToBeTaken)
                .setQtaCnfToBeTaken(qtaCnfToBeTaken)
                .setTotalQtaAvailable(totalQtaAvailable)
                .setTotalNumCnfAvailable(totalNumCnfAvailable)
                .setQtaCnfAvailable(qtaCnfAvailable)
                .setPartitaMag(partitaMag)
                .setDataScad(dataScad)
                .setCanOverflowOrderQuantity(canOverflowOrderQuantity)
                .setCanLUBeClosed(true)
                .setCanPartitaMagBeChanged(canPartitaMagBeChanged)
                .setStatoPartitaMag(pickingObjectDTO != null ? pickingObjectDTO.getStatoArticoloDTO() : null)
                .setNotifyProductLotStatus(SettingsManager.iDB().isNotifyLotStatus());

        if (!mDialogInputQuantityV2View.isVisible())
            mDialogInputQuantityV2View
                    .setDialogInputQuantityV2DTO(dialogInputQuantityV2DTO)
                    .setOnComplete((resultDTO, shouldCloseLU) -> {
                        PickedQuantityDTO pickedQuantityDTO = new PickedQuantityDTO()
                                .setNumCnf(resultDTO.getNumCnf())
                                .setQtaCnf(resultDTO.getQtaCnf())
                                .setQtaTot(resultDTO.getQtaTot())
                                .setPartitaMag(resultDTO.getPartitaMag())
                                .setDataScad(resultDTO.getDataScad());

                        this.onLoadingStarted();
                        onComplete.run(pickedQuantityDTO, shouldCloseLU);
                    })
                    .setOnAbort(() -> {
                        this.mViewmodel.resetMatchedRows();
                    })
                    .show(getSupportFragmentManager(), "tag");
        else Toast.makeText(this, "Dialog già a video", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLUPositionChangeRequest(RunnableArgss<Boolean, MtbDepoPosizione> onComplete) {
        DialogYesNoView.newInstance(null, "Vuoi cambiare la posizione della UL corrente?", result -> {
            switch (result) {
                case YES:
                    DialogAskPositionOfLUView.makeBase(false, (status, mtbDepoPosizione) -> {
                        if (status == DialogConsts.Results.ABORT) {
                            onComplete.run(false, null);
                        } else {
                            onComplete.run(true, mtbDepoPosizione);
                        }
                    }, this::onError).show(getSupportFragmentManager(), "tag");
                    break;

                case NO:
                    onComplete.run(false, null);
                    break;
            }
        }).show(getSupportFragmentManager(), "tag");
    }

    public void askShouldPrintPackingList(PrintOrderCloseDTO printOrderCloseDTO, RunnableArgs<PrintOrderCloseDTO> onComplete) {
        DialogSimpleMessageView.makeInfoDialog(
                        getResources().getString(R.string.action_close_order),
                        new SpannableString(getResources().getString(R.string.message_print_packing_list_on_close_order)),
                        null,
                        () -> {
                            printOrderCloseDTO.setFlagPrintPackingList(true);
                            if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) {
                                this.askShouldPrintSSCC(printOrderCloseDTO, onComplete);
                            } else {
                                onComplete.run(printOrderCloseDTO);
                            }
                        },
                        () -> {
                            printOrderCloseDTO.setFlagPrintPackingList(false);
                            if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) {
                                this.askShouldPrintSSCC(printOrderCloseDTO, onComplete);
                            } else {
                                onComplete.run(printOrderCloseDTO);
                            }
                        }
                )
                .show(getSupportFragmentManager(), "tag");
    }

    public void askShouldPrintSSCC(PrintOrderCloseDTO printOrderCloseDTO, RunnableArgs<PrintOrderCloseDTO> onComplete) {
        DialogPrintOrderSSCCListView.newInstance(printOrderCloseDTO, onComplete).show(this.getSupportFragmentManager(), "dialogPrintOrderSSCCListView");
    }

    @Override
    public void onBatchLotSelectionRequest(List<MtbPartitaMag> availableBatchLots, RunnableArgs<MtbPartitaMag> onComplete) {
        DialogChooseBatchLotView.newInstance(availableBatchLots, onComplete)
                .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onCloseOrderPrintRequest(RunnableArgs<PrintOrderCloseDTO> onComplete) {
        PrintOrderCloseDTO printOrderCloseDTO = new PrintOrderCloseDTO();
        if (SettingsManager.iDB().isFlagPrintPackingListOnOrderClose()) {
            this.askShouldPrintPackingList(printOrderCloseDTO, onComplete);
        } else if (SettingsManager.iDB().isFlagPrintEtichetteOnOrderClose()) {
            this.askShouldPrintSSCC(printOrderCloseDTO, onComplete);
        }

    }

    @Override
    public void onCreateDocsRequest() {
        DialogYesNoView.newInstance("Chiusura ordine", "Vuoi creare i documenti per gli ordini selezionati?", result -> {

            switch (result) {
                case YES:
                    this.mViewmodel.createDocs();
                    break;
                case NO:
                    this.onOrderClosed();
                    break;
            }

        }).show(this.getSupportFragmentManager(), "tag");
    }

    @Override
    public void onChooseArtRequest(List<MtbAart> artsList, RunnableArgs<MtbAart> onComplete) {
        new DialogChooseArtFromListaArtsView(artsList, onComplete)
                .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onChooseArtsRequest(List<MtbAart> artsList, RunnableArgs<List<MtbAart>> onComplete) {
        DialogChooseArtsFromMtbAartListView.newInstance(artsList, onComplete, this::onLoadingEnded)
                .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onOrderClosed() {
        this.onLoadingEnded();
        this.onBackPressed();
    }

    @Override
    public void onRowSaved() {
        FBToast.successToast(this, getResources().getString(R.string.data_saved), FBToast.LENGTH_SHORT);
    }

    @Override
    public void onBottomSheetLUClose() {
        this.mViewmodel.requestCloseLU(true);
    }

    @Override
    public void onMtbColrEdit(MtbColr mtbColr) {
        this.mViewmodel.dispatchRowEdit(mtbColr);
    }

    @Override
    public void onMtbColrDelete(MtbColr mtbColr) {
        this.mViewmodel.requestDeleteRow(mtbColr);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Check which request we're responding to
        if (requestCode == PICK_UL_REQUEST) {

            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                MtbColt recoveredMtbColt = DataCache.retrieveItem(data.getStringExtra("key"));
                this.mViewmodel.recoverLU(recoveredMtbColt);
            }
        }
    }

    @Override
    public void onInfoAggiuntiveRequired(MtbColt mtbColt, RunnableArgss<String, MtbTCol> onComplete) {
        DialogInfoAggiuntiveLU.newInstance(mtbColt, onComplete).show(getSupportFragmentManager(), "InfoAggiuntiveLUDialog");
    }
}
