package it.integry.integrywmsnative.gest.accettazione_bolla_picking;

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.view.Gravity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.databinding.ObservableArrayList;
import androidx.preference.PreferenceManager;

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

import java.math.BigDecimal;
import java.time.LocalDate;
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.BaseActivity;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.expansion.RunnableArgss;
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.MtbTCol;
import it.integry.integrywmsnative.core.model.dto.AlreadyRegisteredUDCDTO;
import it.integry.integrywmsnative.core.model.secondary.GestioneEnum;
import it.integry.integrywmsnative.core.report.ReportManager;
import it.integry.integrywmsnative.core.rest.model.VersamentoAutomaticoULResponseDTO;
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.UtilityToast;
import it.integry.integrywmsnative.databinding.ActivityAccettazioneBollaPickingBinding;
import it.integry.integrywmsnative.gest.accettazione_bolla_elenco.rest.dto.SitBollaAccettazioneDTO;
import it.integry.integrywmsnative.gest.accettazione_bolla_elenco.rest.dto.TestataBollaAccettazioneDTO;
import it.integry.integrywmsnative.gest.accettazione_bolla_picking.dto.AccettazioneBollaPickingOrderBy;
import it.integry.integrywmsnative.gest.accettazione_bolla_picking.dto.PickingObjectDTO;
import it.integry.integrywmsnative.gest.accettazione_bolla_picking.ui.AccettazioneBollaPickingListAdapter;
import it.integry.integrywmsnative.gest.accettazione_bolla_picking.ui.AccettazioneBollaPickingListModel;
import it.integry.integrywmsnative.gest.lista_bancali.ListaBancaliActivity;
import it.integry.integrywmsnative.gest.spedizione.exceptions.InvalidPesoKGException;
import it.integry.integrywmsnative.gest.spedizione.model.PickedQuantityDTO;
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.ask_should_versamento_automatico_ul.DialogAskShouldVersamentoAutomaticoULView;
import it.integry.integrywmsnative.view.dialogs.ask_unknown_barcode_notes.DialogAskUnknownBarcodeNotesView;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;
import it.integry.integrywmsnative.view.dialogs.bind_product_barcode_with_package.DialogBindProductBarcodeWithPackageView;
import it.integry.integrywmsnative.view.dialogs.info_aggiuntive_lu.DialogInfoAggiuntiveLUView;
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.versamento_automatico_ul_done.DialogVersamentoAutomaticoULDoneView;

public class AccettazioneBollaPickingActivity extends BaseActivity implements AccettazioneBollaPickingViewModel.Listener, BottomSheetFragmentLUContentViewModel.Listener, BottomSheetFragmentLUContentView.Listener {


    @Inject
    AccettazioneBollaPickingViewModel mViewModel;

    @Inject
    DialogInputQuantityV2View mDialogInputQuantityV2View;

    private ActivityAccettazioneBollaPickingBinding mBindings;

    private BottomSheetFragmentLUContentViewModel mBottomSheetFragmentLUContentViewModel;


    private final ObservableArrayList<AccettazioneBollaPickingListModel> mAccettazioneMutableData = new ObservableArrayList<>();

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

    private int barcodeScannerIstanceID = -1;
    private boolean mShowSecondaryUntMis = true;
    private boolean mShouldCloseActivity;
    private AccettazioneBollaPickingOrderBy.Enum mCurrentOrderBy;

    private final int PICK_UL_REQUEST = 1;

    private List<TestataBollaAccettazioneDTO> testataBolle;
    private List<SitBollaAccettazioneDTO> sitArts;


    private PopupMenu fabPopupMenu;


    //Pass here all external parameters
    public static void startActivity(Context context, List<TestataBollaAccettazioneDTO> testataBolle, List<SitBollaAccettazioneDTO> sitArts) {
        Intent myIntent = new Intent(context, AccettazioneBollaPickingActivity.class);

        String keyBolle = DataCache.addItem(testataBolle);
        myIntent.putExtra("keyBolle", keyBolle);

        String keySitArts = DataCache.addItem(sitArts);
        myIntent.putExtra("keySitArts", keySitArts);

        context.startActivity(myIntent);
    }


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

        testataBolle = DataCache.retrieveItem(getIntent().getStringExtra("keyBolle"));
        sitArts = DataCache.retrieveItem(getIntent().getStringExtra("keySitArts"));

        mBindings = ActivityAccettazioneBollaPickingBinding.inflate(getLayoutInflater());
        mBindings.setLifecycleOwner(this);
        mBindings.setView(this);

        setContentView(mBindings.getRoot());

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


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

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

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mShowSecondaryUntMis = sharedPreferences.getBoolean("picking_ingresso_enable_sec_unt_mis", true);

        this.initVars();
        this.initBarcodeReader();
        this.initRecyclerView();
//        this.initFilters();
        this.initFab();

        boolean useQtaBolla = SettingsManager.iDB().isFlagAccettazioneUseQtaOrd();

        mViewModel.setListeners(this);
        mViewModel.init(
                testataBolle,
                sitArts,
                useQtaBolla);
    }

    @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.closeLU();
        } else {
            BarcodeManager.removeCallback(barcodeScannerIstanceID);
            super.onBackPressed();
        }
    }

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

        mCurrentOrderBy = AccettazioneBollaPickingOrderBy.Enum.fromInt(SettingsManager.i().getUserSession().getDefaultOrdinamentoPickingAccettazioneBolle());
    }

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

    private void initRecyclerView() {
        AccettazioneBollaPickingListAdapter adapter = new AccettazioneBollaPickingListAdapter(this, mAccettazioneMutableData, mShowSecondaryUntMis);
        this.mBindings.accettazionePickingList.setAdapter(adapter);

        this.mViewModel.getPickingList().observe(this, updatedData -> {
//            mAppliedFilterViewModel.init(updatedData);

            refreshList();
        });

        adapter.setOnItemClicked(clickedItem -> {
            this.mViewModel.dispatchBollaRow(clickedItem);
        });
    }


    private void initFab() {
        fabPopupMenu = new PopupMenu(this, this.mBindings.accettazioneOrdineInevasoFab,
                (Gravity.END | Gravity.BOTTOM),
                androidx.appcompat.R.attr.popupMenuStyle,
                com.google.android.material.R.style.Widget_Material3_PopupMenu_ContextMenu);

        fabPopupMenu.setForceShowIcon(true);
        fabPopupMenu.getMenuInflater().inflate(R.menu.accettazione_ordine_inevaso_fab_menu, fabPopupMenu.getMenu());

        fabPopupMenu.getMenu().findItem(R.id.show_created_ul).setVisible(SettingsManager.iDB().isFlagAllowULRecoverAccettazioneBolla());

        fabPopupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();

            if (itemId == R.id.show_created_ul) {
                showCreatedUL();
            } else if (itemId == R.id.create_ul) {
                createNewLU();
            }

            return false;
        });
    }


    public void showFabMenu() {
        fabPopupMenu.show();
    }

    private void refreshList() {

        runOnUiThread(() -> {
            List<PickingObjectDTO> tmpList;

//            if (mAppliedFilterViewModel != null) {
//                mAppliedFilterViewModel.applyAllTests();
//                tmpList = mAppliedFilterViewModel.getMutableFilteredOrderList().getValue();
//            } else {
            tmpList = mViewModel.getPickingList().getValue();
//            }
//
            var list = convertDataModelToListModel(tmpList);

            this.mAccettazioneMutableData.clear();
            this.mAccettazioneMutableData.addAll(list);
            this.noItemsToPick.set(!isThereAnyItemToPick(tmpList));

        });
    }

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

    private List<AccettazioneBollaPickingListModel> convertDataModelToListModel(List<PickingObjectDTO> dataList) {
        List<PickingObjectDTO> tmpList = Stream.of(dataList)
                .filter(x -> !x.isHidden() && UtilityBigDecimal.greaterThan(x.getSitBollaAccettazione().getQtaDaAccettare(), BigDecimal.ZERO))
                .toList();

        return switch (mCurrentOrderBy) {
            case COD_ART_FOR -> convertDataModelToListModel__NormalView(
                    tmpList,
                    ComparatorCompat
                            .comparing(x -> x.getSitBollaAccettazione().getCodArtFor()));
            case DESCR_ART -> //convertDataModelToListModel__DescrArt(tmpList);
                    new ArrayList<>();
        };
    }

    private List<AccettazioneBollaPickingListModel> convertDataModelToListModel__NormalView(List<PickingObjectDTO> dataList, ComparatorCompat<PickingObjectDTO> comparator) {
        ArrayList<AccettazioneBollaPickingListModel> list = new ArrayList<>();
        Stream.of(dataList)
                .sorted(comparator)
                .forEach(x -> {
                    AccettazioneBollaPickingListModel accettazioneBollaPickingListModel = new AccettazioneBollaPickingListModel();
                    accettazioneBollaPickingListModel.setActive(true);

                    accettazioneBollaPickingListModel.setTitolo(x.getMtbAart().getCodMart());

                    accettazioneBollaPickingListModel.setBadge2Icon(R.drawable.ic_document_outline);
                    accettazioneBollaPickingListModel.setBadge2(x.getSitBollaAccettazione().getNumDoc() + " del " + UtilityDate.formatDate(x.getSitBollaAccettazione().getDataDoc(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN));

                    accettazioneBollaPickingListModel.setDescrizione(x.getMtbAart().getDescrizione());

                    //Calc Num CNF
                    BigDecimal numCnfEvasa = BigDecimal.ZERO;

                    if (x.getWithdrawMtbColrs().size() > 0) {
                        numCnfEvasa = Stream.of(x.getWithdrawMtbColrs())
                                .map(MtbColr::getNumCnf)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                    }

                    //Calc qta col
                    BigDecimal qtaEvasa = BigDecimal.ZERO;

                    if (x.getWithdrawMtbColrs().size() > 0) {
                        qtaEvasa = Stream.of(x.getWithdrawMtbColrs())
                                .map(MtbColr::getQtaCol)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                    }


                    if (SettingsManager.iDB().isFlagForceAllToColli() || (x.getMtbAart() == null || !x.getMtbAart().isFlagQtaCnfFissaBoolean())) {
                        accettazioneBollaPickingListModel.setQtaEvasa(numCnfEvasa);
                        accettazioneBollaPickingListModel.setQtaTot(x.getSitBollaAccettazione().getNumCnfDaAccettare());
                        accettazioneBollaPickingListModel.setUntMis(UtilityResources.getString(R.string.unt_mis_col));

                        accettazioneBollaPickingListModel.setSecQtaEvasa(qtaEvasa);
                        accettazioneBollaPickingListModel.setSecQtaTot(x.getSitBollaAccettazione().getQtaDaAccettare());
                        if (x.getMtbAart() != null)
                            accettazioneBollaPickingListModel.setSecUntMis(x.getMtbAart().getUntMis());
                    } else {
                        accettazioneBollaPickingListModel.setQtaEvasa(qtaEvasa);
                        accettazioneBollaPickingListModel.setQtaTot(x.getSitBollaAccettazione().getQtaDaAccettare());
                        if (x.getMtbAart() != null)
                            accettazioneBollaPickingListModel.setUntMis(x.getMtbAart().getUntMis());

                        accettazioneBollaPickingListModel.setSecQtaEvasa(numCnfEvasa);
                        accettazioneBollaPickingListModel.setSecQtaTot(x.getSitBollaAccettazione().getNumCnfDaAccettare());
                        accettazioneBollaPickingListModel.setSecUntMis(UtilityResources.getString(R.string.unt_mis_col));
                    }

                    accettazioneBollaPickingListModel.setOriginalModel(x);

                    list.add(accettazioneBollaPickingListModel);
                });

        return list;
    }


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

        this.mViewModel.processBarcodeDTO(data, this::onLoadingEnded);
    };

    public void createNewLU() {
        this.fabPopupMenu.dismiss();
        this.onLoadingStarted();
        this.mViewModel.createNewLU(null, null, false, this::onLoadingEnded);
    }

    public void showCreatedUL() {
        this.fabPopupMenu.dismiss();
        this.mViewModel.retrieveExistentLU(this::startListaBancaliRegistratiActivity);
    }

    private void showOrderByDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(this.getText(R.string.action_orderBy))
                .setSingleChoiceItems(AccettazioneBollaPickingOrderBy.descriptions, mCurrentOrderBy.getVal(), (dialog12, which) -> {
                    mCurrentOrderBy = AccettazioneBollaPickingOrderBy.Enum.fromInt(which);
                    SettingsManager.i().getUserSession().setDefaultOrdinamentoPickingAccettazione(which);
                })
                .setPositiveButton(getText(R.string.ok), (dialog1, which) -> this.refreshList())
                .create();
        dialog.show();
    }

    public void startListaBancaliRegistratiActivity(List<AlreadyRegisteredUDCDTO> mtbColts) {

        Intent myIntent = ListaBancaliActivity.createIntent(this,

                Stream.of(mtbColts)
                        .map(AlreadyRegisteredUDCDTO::getMtbColt)
                        .toList(),

                input -> Stream.of(mtbColts)
                        .filter(x -> x.getMtbColt() == input)
                        .findFirstOrElse(null)
                        .isCanBeRecovered(),

                ReportManager.getReportNameLUFromGestione(GestioneEnum.ACQUISTO));

        this.startActivityForResult(myIntent, PICK_UL_REQUEST);
    }

    @Override
    public void onMtbColrDeleteRequest(RunnableArgs<Boolean> onComplete) {
        runOnUiThread(() -> {
            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 onLUOpened(MtbColt mtbColt) {
        runOnUiThread(() -> {
            noLUPresent.set(false);
            FBToast.successToast(this, getResources().getString(R.string.data_saved), FBToast.LENGTH_SHORT);

            this.mBottomSheetFragmentLUContentViewModel.setMtbColt(mtbColt);
        });
    }

    @Override
    public void onLUClosed() {
        runOnUiThread(() -> {
            noLUPresent.set(true);
            this.mBottomSheetFragmentLUContentViewModel.setMtbColt(null);

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

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

    @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) {

    }

    @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 onMtbColrEdit(MtbColr mtbColr) {
        this.mViewModel.dispatchRowEdit(mtbColr);
    }

    @Override
    public void onMtbColrDelete(MtbColr mtbColr) {
        this.mViewModel.deleteRow(mtbColr);
    }

    @Override
    public void onBottomSheetLUClose() {
        this.mViewModel.closeLU();
    }

    @Override
    public void onVersamentoAutomaticoULRequest(RunnableArgs<Boolean> onComplete) {
        runOnUiThread(() -> {
            DialogAskShouldVersamentoAutomaticoULView.newInstance(onComplete)
                    .show(getSupportFragmentManager(), "tag");
        });
    }

    @Override
    public void onInfoAggiuntiveRequest(RunnableArgss<String, MtbTCol> onComplete) {
        DialogInfoAggiuntiveLUView.newInstance(onComplete, this::onLoadingEnded)
                .show(getSupportFragmentManager(), DialogInfoAggiuntiveLUView.class.getName());
    }

    @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 onItemDispatched(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, LocalDate dataScad, boolean canPartitaMagBeChanged,
                                 boolean canOverflowQuantity, 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)
                .setCanPartitaMagBeChanged(canPartitaMagBeChanged)
                .setCanLUBeClosed(true)
                .setCanOverflowOrderQuantity(canOverflowQuantity)
                .setDisableTracciabilitaCheck(SettingsManager.iDB().isFlagDisableMandatoryTracciabilitaAccettazioneBolla());

        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());
                        onComplete.run(pickedQuantityDTO, shouldCloseLU);
                    })
                    .setOnAbort(() -> this.mViewModel.resetMatchedRows())
                    .show(getSupportFragmentManager(), "tag");
    }

    @Override
    public void onFilterCodMartApplied(String codMartToFilter) {
        runOnUiThread(() -> {
            var codMarts = new ArrayList<String>();
            codMarts.add(codMartToFilter);

//            this.mAppliedFilterViewModel.setCodArtFilter(codMarts);
        });
    }

    @Override
    public void onFilterPosizioneApplied(String posizioneToFilter) {
        runOnUiThread(() -> {
            var posizioni = new ArrayList<String>();
            posizioni.add(posizioneToFilter);

//            this.mAppliedFilterViewModel.setPosFilter(posizioni);
        });
    }

    @Override
    public void onULVersata(VersamentoAutomaticoULResponseDTO
                                    versamentoAutomaticoULResponseDTO, Runnable onComplete) {

        runOnUiThread(() -> {
            DialogVersamentoAutomaticoULDoneView
                    .newInstance(versamentoAutomaticoULResponseDTO, onComplete)
                    .show(getSupportFragmentManager(), "tag");
        });
    }

    @Override
    public void onUnknownBarcodeScanned(String barcode, RunnableArgs<String> done, Runnable abort) {
        DialogAskUnknownBarcodeNotesView
                .newInstance(barcode, done, abort)
                .show(getSupportFragmentManager(), DialogBindProductBarcodeWithPackageView.class.getName());
    }

    @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);
            }
        }
    }
}