package it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.MultiAutoCompleteTextView;

import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;

import com.annimon.stream.Stream;

import java.util.List;
import java.util.Objects;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.di.BindableString;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.databinding.DialogOrdineProduzioneFiltroAvanzatoBinding;
import it.integry.integrywmsnative.gest.accettazione.dto.OrdineAccettazioneInevasoDTO;

public class DialogOrdineProduzioneFiltroAvanzatoView {


    private AlertDialog currentAlert;
    private Context currentContext;

    private RunnableArgs<DialogOrdineProduzioneFiltroAvanzatoViewModel> currentOnFilterDone;

    public BindableString numOrds = new BindableString();
    public BindableString codJcoms = new BindableString();

    private ArrayAdapter<String> arrayAdapterNumOrds;
    private ArrayAdapter<String> arrayAdapterCodJcoms;

    private DialogOrdineProduzioneFiltroAvanzatoViewModel mViewModel;



    public static AlertDialog make(final Context context,
                                   final List<OrdineAccettazioneInevasoDTO> ordersList,
                                   DialogOrdineProduzioneFiltroAvanzatoViewModel baseViewModel,
                                   RunnableArgs<DialogOrdineProduzioneFiltroAvanzatoViewModel> onDismiss) {
        return new DialogOrdineProduzioneFiltroAvanzatoView(context, ordersList, baseViewModel, onDismiss).currentAlert;
    }


    private DialogOrdineProduzioneFiltroAvanzatoView(final Context context, final List<OrdineAccettazioneInevasoDTO> ordersList, DialogOrdineProduzioneFiltroAvanzatoViewModel baseViewModel, RunnableArgs<DialogOrdineProduzioneFiltroAvanzatoViewModel> onDismiss) {
        currentContext = context;
        currentOnFilterDone = onDismiss;

        mViewModel = baseViewModel != null ? baseViewModel : new DialogOrdineProduzioneFiltroAvanzatoViewModel();
        mViewModel.init(ordersList);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        DialogOrdineProduzioneFiltroAvanzatoBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_ordine_produzione_filtro_avanzato, null, false);

        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
                .setView(binding.getRoot());

        binding.setView(this);
        binding.setViewmodel(mViewModel);
        initViewModel(mViewModel);
        initView(binding);

        currentAlert = alertDialog.create();
        currentAlert.setCanceledOnTouchOutside(false);

        currentAlert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        currentAlert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        binding.positiveBtn.setOnClickListener(view -> {
            currentAlert.dismiss();
        });

        binding.neutralBtn.setOnClickListener(view -> {
            resetAll();
        });


        currentAlert.setOnDismissListener(dialogInterface -> {
            if(currentOnFilterDone != null) currentOnFilterDone.run(mViewModel);
        });
    }

    private void initView(DialogOrdineProduzioneFiltroAvanzatoBinding bindings) {

        arrayAdapterNumOrds = new ArrayAdapter(currentContext, R.layout.dialog_vendita_filtro_avanzato__single_item);
        arrayAdapterNumOrds.addAll(getAvailableNumOrds(false));
        bindings.filledExposedDropdownNumOrds.setAdapter(arrayAdapterNumOrds);
        bindings.filledExposedDropdownNumOrds.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

        arrayAdapterCodJcoms = new ArrayAdapter(currentContext, R.layout.dialog_vendita_filtro_avanzato__single_item);
        arrayAdapterCodJcoms.addAll(getAvailableCodJcoms(false));
        bindings.filledExposedDropdownCodJcoms.setAdapter(arrayAdapterCodJcoms);
        bindings.filledExposedDropdownCodJcoms.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());


        refreshAll();
    }


    private void initViewModel(DialogOrdineProduzioneFiltroAvanzatoViewModel viewModel) {
        viewModel.applyAllTests();

        BindableString.registerListener(numOrds, value -> {
            viewModel.setNumOrdFilter(value);
            viewModel.applyAllTests();

            refreshArrayAdapter(arrayAdapterCodJcoms, getAvailableCodJcoms(true));
        });

        BindableString.registerListener(codJcoms, value -> {
            viewModel.setCodJcomFilter(value);
            viewModel.applyAllTests();

            refreshArrayAdapter(arrayAdapterNumOrds, getAvailableNumOrds(true));
        });

    }


    private void refreshArrayAdapter(ArrayAdapter<String> arrayAdapter, List<String> inputList) {
        arrayAdapter.clear();
        arrayAdapter.addAll(inputList);
        arrayAdapter.notifyDataSetChanged();
    }


    private List<String> getAvailableNumOrds(boolean skipRecalc) {
        return Stream.of(Objects.requireNonNull(mViewModel.getMutableFilteredOrderList().getValue()))
                .map(x -> x.getNumero().toString())
                .distinct()
                .withoutNulls()
                .sorted()
                .toList();
    }


    private List<String> getAvailableCodJcoms(boolean skipRecalc) {
        return Stream.of(Objects.requireNonNull(mViewModel.getMutableFilteredOrderList().getValue()))
                .map(OrdineAccettazioneInevasoDTO::getCodJcom)
                .distinct()
                .withoutNulls()
                .sorted()
                .toList();
    }


    public void refreshAll() {
        numOrds.refresh();
        codJcoms.refresh();
    }


    public void resetAll() {
        numOrds.set(null);
        codJcoms.set(null);
    }
}
