package it.integry.integrywmsnative.view.dialogs.info_aggiuntive_lu;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;

import com.annimon.stream.Optional;
import com.annimon.stream.Stream;

import org.jetbrains.annotations.NotNull;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgss;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.model.MtbTCol;
import it.integry.integrywmsnative.core.utility.UtilityDialog;
import it.integry.integrywmsnative.core.utility.UtilityObservable;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.databinding.DialogNoteAggiuntiveNuovaUlBinding;
import it.integry.integrywmsnative.view.dialogs.input_lu_prod.adapter.DialogInputLUProdTipoColloAdapter;
import it.integry.integrywmsnative.view.dialogs.input_lu_prod.adapter.DialogInputLUProdTipoColloListModel;

public class DialogInfoAggiuntiveLU extends BaseDialogFragment implements InfoAggiuntiveLUDialogViewModel.Listener {

    @Inject
    InfoAggiuntiveLUDialogViewModel mViewModel;

    private DialogNoteAggiuntiveNuovaUlBinding mBindings;
    private final RunnableArgss<String, MtbTCol> mOnComplete;
    private MtbColt currentMtbColt;
    private DialogInputLUProdTipoColloAdapter codTcolArrayAdapter = null;
    public ObservableField<String> additionalNotes = new ObservableField<>();
    public ObservableField<String> selectedMtbTcol = new ObservableField<>();
    public ObservableField<DialogInputLUProdTipoColloListModel> currentMtbTCol = new ObservableField<>();

    public static DialogInfoAggiuntiveLU newInstance(@NotNull RunnableArgss<String, MtbTCol> onComplete) {
        return new DialogInfoAggiuntiveLU(null, onComplete);
    }

    public static DialogInfoAggiuntiveLU newInstance(MtbColt mtbColt, @NotNull RunnableArgss<String, MtbTCol> onComplete) {
        return new DialogInfoAggiuntiveLU(mtbColt, onComplete);
    }

    private DialogInfoAggiuntiveLU(MtbColt mtbColt, @NotNull RunnableArgss<String, MtbTCol> onComplete) {
        super();
        this.mOnComplete = onComplete;
        this.currentMtbColt = mtbColt;
    }


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

        UtilityDialog.setTo90PercentWidth(requireActivity(), this);
        this.mViewModel.setListener(this);
        this.mViewModel.init();
    }

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

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

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

        mBindings.setView(this);
        mBindings.setViewModel(this.mViewModel);

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setCancelable(false);
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);


        return mBindings.getRoot();
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        if (mOnComplete != null)
            mOnComplete.run(additionalNotes.get(), mViewModel.getInternalTipoPed());
        super.onDismiss(dialog);
    }


    private void init() {


        UtilityObservable.addPropertyChanged(this.selectedMtbTcol, (value) -> {
            if (this.codTcolArrayAdapter != null && this.codTcolArrayAdapter.getDataset() != null) {
                Optional<DialogInputLUProdTipoColloListModel> selectedItem = Stream.of(this.codTcolArrayAdapter.getDataset())
                        .filter(x -> x.toString().equals(value))
                        .findFirst();

                if (selectedItem.isPresent()) {
                    currentMtbTCol.set(selectedItem.get());
                    this.mViewModel.setInternalTipoPed(selectedItem.get().getOriginalModel());
                }
            }
        });

        this.mViewModel.getTipiCollo().observe(getViewLifecycleOwner(), tipiCollo -> {


            codTcolArrayAdapter = new DialogInputLUProdTipoColloAdapter(getActivity(), R.layout.array_adapter_single_item, tipiCollo);
            mBindings.filledExposedDropdownCodTcol.setAdapter(codTcolArrayAdapter);

            if (currentMtbColt != null && !UtilityString.isNullOrEmpty(currentMtbColt.getCodTcol()) && UtilityString.isNullOrEmpty(this.selectedMtbTcol.get())) {
                MtbTCol tipoPedana = Stream.of(tipiCollo).filter(x -> x.getCodTcol().equalsIgnoreCase(currentMtbColt.getCodTcol())).findFirstOrElse(null);
                if (tipoPedana != null) {
                    this.selectedMtbTcol.set(tipoPedana.getCodTcol() + " - " + tipoPedana.getDescrizione());
                }
            }

        });

        this.mBindings.filledExposedDropdownCodTcol.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                currentMtbTCol.set(codTcolArrayAdapter.getItem(i));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                currentMtbTCol.set(null);
            }
        });

        mBindings.buttonConfirm.setOnClickListener(v -> {
            dismiss();
        });

        if (this.currentMtbColt != null) {
            this.additionalNotes.set(currentMtbColt.getAnnotazioni());
        }
    }
}
