package it.integry.integrywmsnative.gest.prod_fabbisogno_linee_prod;

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

import androidx.appcompat.widget.AppCompatTextView;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.annimon.stream.Stream;

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

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.expansion.BaseFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.secondary.GestioneEnum;
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.UtilityExceptions;
import it.integry.integrywmsnative.databinding.FragmentProdFabbisognoLineeProdBinding;
import it.integry.integrywmsnative.gest.prod_fabbisogno_linee_prod.dialog_ask_mag_prossimita.DialogAskMagazzinoProssimitaView;
import it.integry.integrywmsnative.gest.prod_fabbisogno_linee_prod.dto.ProdFabbisognoLineeProdDTO;
import it.integry.integrywmsnative.gest.spedizione.SpedizioneActivity;
import it.integry.integrywmsnative.gest.spedizione.dialogs.row_info.prod_fabbisogno_linee_prod.DialogRowInfoProdFabbisognoLineeProdView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProdFabbisognoLineeProdFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProdFabbisognoLineeProdFragment extends BaseFragment implements ITitledFragment, ProdFabbisognoLineeProdViewModel.Listener {

    @Inject
    ProdFabbisognoLineeProdViewModel mViewModel;

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

    private FragmentProdFabbisognoLineeProdBinding mBindings;

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

    public static ProdFabbisognoLineeProdFragment newInstance() {
        ProdFabbisognoLineeProdFragment fragment = new ProdFabbisognoLineeProdFragment();
        return fragment;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBindings = DataBindingUtil.inflate(inflater, R.layout.fragment_prod_fabbisogno_linee_prod, container, false);

        mBindings.setLifecycleOwner(this);

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


        return mBindings.getRoot();
    }

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

        this.mViewModel.setListener(this);

        String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep();

        DialogAskMagazzinoProssimitaView
                .newInstance((jtbFase, startDate, endDate) -> {
//                    if (jtbFase == null) {
//                        ((IPoppableActivity) getActivity()).pop();
//                    } else {
                        //Load fabbisogno
                        this.mViewModel.loadFabbisogno(startDate, endDate, codMdep, this::startPickingActivity);
//                    }
                })
                .show(getActivity().getSupportFragmentManager(), "tag");
    }


    @Override
    public void onDestroy() {
        for (Runnable onPreDestroy : mOnPreDestroyList) {
            onPreDestroy.run();
        }

        super.onDestroy();
    }

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


    @Override
    public void onError(Exception ex) {
        this.closeProgress();
        UtilityExceptions.defaultException(getActivity(), ex);
    }

    @Override
    public void onLoadingStarted() {
        this.openProgress();
    }

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


    private void startPickingActivity(List<ProdFabbisognoLineeProdDTO> fabbisognoList) {
        String codMdep = SettingsManager.i().getUserSession().getDepo().getCodMdep();

        List<SitArtOrdDTO> sitArtOrdDTOS = Stream.of(fabbisognoList)
                .map(x -> {
                    SitArtOrdDTO sitArtOrdDTO = new SitArtOrdDTO()
                            .setCodMart(x.getCodMart())
                            .setCodMdep(codMdep)
                            .setQtaOrd(x.getQtaFabbisogno())
                            .setNumCnfOrd(x.getNumCnfFabbisogno())
                            .setQtaCnfOrd(UtilityBigDecimal.divide(x.getQtaFabbisogno(), x.getNumCnfFabbisogno()))
                            .setFlagEnablePickManuale(false);

                    sitArtOrdDTO.getExtraInfo().put("dataInizio", x.getDataInizio());
                    sitArtOrdDTO.getExtraInfo().put("dataFine", x.getDataFine());

                    return sitArtOrdDTO;
                })
                .toList();

        SpedizioneActivity.startActivity(getActivity(),
                sitArtOrdDTOS,
                null,
                new ArrayList<>(),
                GestioneEnum.LAVORAZIONE,
                +1,
                MtbColr.Causale.VERSAMENTO,
                DialogRowInfoProdFabbisognoLineeProdView.class);

        popMe();

    }

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