package it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione;


import android.content.Context;
import android.content.Intent;
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.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.annimon.stream.Stream;

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

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
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.interfaces.IFilterableFragment;
import it.integry.integrywmsnative.core.interfaces.IScrollableFragment;
import it.integry.integrywmsnative.core.interfaces.ITitledFragment;
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.databinding.FragmentProdOrdineProduzioneElencoBinding;
import it.integry.integrywmsnative.gest.accettazione.dto.OrdineAccettazioneInevasoDTO;
import it.integry.integrywmsnative.gest.accettazione.dto.SitArtOrdDTO;
import it.integry.integrywmsnative.gest.accettazione_picking.AccettazionePickingActivity;
import it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.dialog.DialogOrdineProduzioneFiltroAvanzatoView;
import it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.dialog.DialogOrdineProduzioneFiltroAvanzatoViewModel;
import it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.ui.MainListProdOrdineProduzioneElencoClienteListModel;
import it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.ui.MainListProdOrdineProduzioneElencoListModel;
import it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.ui.OrdineProduzioneListAdapter;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProdOrdineProduzioneElencoFragment extends BaseFragment implements ProdOrdineProduzioneElencoViewModel.Listener, ITitledFragment, IScrollableFragment, IFilterableFragment {

    public BindableBoolean fabVisible = new BindableBoolean(false);

    @Inject
    ProdOrdineProduzioneElencoViewModel mViewModel;

    private FragmentProdOrdineProduzioneElencoBinding mBinding;

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

    private AppCompatTextView mAppBarTitle;

    private DialogOrdineProduzioneFiltroAvanzatoViewModel mAppliedFilterViewModel;


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


    public static ProdOrdineProduzioneElencoFragment newInstance() {
        ProdOrdineProduzioneElencoFragment fragment = new ProdOrdineProduzioneElencoFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

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


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

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

        mViewModel.setListener(this);

        mBinding.setLifecycleOwner(this);
        mBinding.setView(this);

        this.initRecyclerView();

        return mBinding.getRoot();
    }


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

        this.fabVisible.set(false);

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

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

    private void initRecyclerView() {
        this.mViewModel.getOrderList().observe(getViewLifecycleOwner(), this::refreshList);

        mBinding.ordineProduzioneMainList.setLayoutManager(new LinearLayoutManager(getActivity()));

        OrdineProduzioneListAdapter adapter = new OrdineProduzioneListAdapter(getActivity(), mOrdiniInevasiMutableData)
                .setOnGroupItemClicked(x -> {
                    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 -> {
                    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()));
                });

        adapter.setEmptyView(mBinding.ordiniProduzioneEmptyView);

        mBinding.ordineProduzioneMainList.setAdapter(adapter);

        mToolbar.setRecyclerView(mBinding.ordineProduzioneMainList);
    }

    private void refreshList(List<OrdineAccettazioneInevasoDTO> filteredList) {

        List<OrdineAccettazioneInevasoDTO> 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<MainListProdOrdineProduzioneElencoListModel> convertDataModelToListModel(List<OrdineAccettazioneInevasoDTO> dataList) {

        return Stream.of(dataList)
                .distinctBy(OrdineAccettazioneInevasoDTO::getBarcode)
                .sortBy(x -> x.getRagSocOrd() + (x.getDataConsD() != null ? UtilityDate.formatDate(x.getDataConsD(), UtilityDate.COMMONS_DATE_FORMATS.YMD_SLASH) : ""))
                .map(x -> {
                    MainListProdOrdineProduzioneElencoListModel listModel = new MainListProdOrdineProduzioneElencoListModel();

                    listModel.setOriginalModel(x);

                    listModel.setGroupTitle(x.getRagSocOrd());

                    listModel.setDescription(String.format(getString(R.string.ord_acq_testata), x.getNumero().toString(), UtilityDate.formatDate(x.getDataD(), UtilityDate.COMMONS_DATE_FORMATS.DMY_HUMAN)));

                    List<MainListProdOrdineProduzioneElencoClienteListModel> clienti = Stream.of(dataList)
                            .filter(y -> y.getBarcode().equals(x.getBarcode()))
                            .map(y -> new MainListProdOrdineProduzioneElencoClienteListModel()
                                    .setPrimaryText(y.getRifOrd())
                                    .setRightText(y.getCodJcom()))
                            .toList();

                    listModel.setClientiListModel(clienti);

                    return listModel;
                })
                .toList();
    }


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


        this.mViewModel.loadPicking(selectedOrders);
    }

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

                filter -> {

                    mAppliedFilterViewModel = filter;
                    refreshList(null);

                }).show();
    }


    @Override
    public void onOrdersDispatched(List<OrdineAccettazioneInevasoDTO> orders, List<SitArtOrdDTO> sitArts) {
        long artsCounter = Stream.of(sitArts)
                .filter(x -> UtilityBigDecimal.greaterThan(x.getQtaDaEvadere(), BigDecimal.ZERO))
                .map(SitArtOrdDTO::getCodMart)
                .distinct()
                .count();

        long ordsCounter = Stream.of(sitArts)
                .distinctBy(x -> x.getDataOrd() + " " + x.getNumOrd() + " " + x.getGestione())
                .count();


        DialogSimpleMessageView.makeInfoDialog(getText(R.string.orders).toString(),
                Html.fromHtml(String.format(getActivity().getResources().getQuantityString(R.plurals.loaded_orders_message, (int) ordsCounter), ordsCounter)
                        + "<br /><br />" +
                        "<b>" + artsCounter + "</b> " + getActivity().getResources().getQuantityString(R.plurals.available_articles, (int) artsCounter)),
                null,
                () -> {

                    String cacheSitArtItemID = DataCache.addItem(sitArts);
                    String cacheOrdersItemID = DataCache.addItem(orders);

                    Intent myIntent = new Intent(getActivity(), AccettazionePickingActivity.class);
                    myIntent.putExtra("keyOrders", cacheOrdersItemID);
                    myIntent.putExtra("keySitArts", cacheSitArtItemID);
                    getActivity().startActivity(myIntent);

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