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

import android.content.Context;
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.ArrayAdapter;

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

import java.util.Date;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.di.BindableString;
import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityObservable;
import it.integry.integrywmsnative.databinding.DialogSelectDocInfoBinding;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.FornitoreDTO;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.GruppiArticoloDTO;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.DocInterniSetupDTO;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.TipiDocDTO;

public class DialogSelectDocInfoView extends BaseDialogFragment implements DialogSelectDocInfoViewModel.Listener {

    @Inject
    DialogSelectDocInfoViewModel mViewModel;
    private Context mCurrentContext;


    public BindableString codDtip = new BindableString();
    public BindableString codMgrp = new BindableString();
    public BindableString codAnag = new BindableString();
    public BindableString numDoc = new BindableString();
    public BindableString note = new BindableString();
    public ObservableField<Date> dataDoc = new ObservableField<>();

    private ArrayAdapter<String> arrayAdapterCodDtips;
    private ArrayAdapter<String> arrayAdapterCodMgrps;
    private ArrayAdapter<String> arrayAdapterCodAnags;
    private ArrayAdapter<String> arrayAdapterNote;
    private DialogSelectDocInfoBinding mBindings;

    private final RunnableArgs<DialogSelectDocInfoViewModel> currentOnFilterDone;
    private final DocInterniSetupDTO docInterniSetupDTO;
    private final TipiDocDTO selectedDtip;
    private final GruppiArticoloDTO selectedGrp;
    private final FornitoreDTO selectedAnag;
    private final Date selectedDataDoc;
    private final String selectedNumDoc;
    private final String selectedNote;

    public static DialogSelectDocInfoView newInstance(
            DocInterniSetupDTO docInterniSetupDTO,
            TipiDocDTO tipiDocDTO,
            GruppiArticoloDTO gruppiArticoloDTO,
            FornitoreDTO fornitoreDTO,
            Date dataDoc,
            String numDoc,
            String note,
            RunnableArgs<DialogSelectDocInfoViewModel> onDismiss
    ) {
        return new DialogSelectDocInfoView(docInterniSetupDTO, tipiDocDTO, gruppiArticoloDTO, fornitoreDTO, dataDoc, numDoc,note, onDismiss);
    }


    private DialogSelectDocInfoView(DocInterniSetupDTO docInterniSetupDTO,
                                    TipiDocDTO tipiDocDTO,
                                    GruppiArticoloDTO gruppiArticoloDTO,
                                    FornitoreDTO fornitoreDTO,
                                    Date dataDoc,
                                    String numDoc,
                                    String note,
                                    RunnableArgs<DialogSelectDocInfoViewModel> onDismiss) {
        super();
        currentOnFilterDone = onDismiss;
        this.docInterniSetupDTO = docInterniSetupDTO;
        selectedDtip = tipiDocDTO;
        selectedGrp = gruppiArticoloDTO;
        selectedDataDoc = dataDoc;
        selectedNumDoc = numDoc;
        selectedNote = note;
        selectedAnag = fornitoreDTO;
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (currentOnFilterDone != null) currentOnFilterDone.run(mViewModel);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.mCurrentContext = this.requireActivity();

        mBindings = DataBindingUtil.inflate(inflater, R.layout.dialog_select_doc_info, container, false);
        mBindings.setLifecycleOwner(this);

        MainApplication
                .appComponent
                .dialogSelectMgrpDtipPairComponent()
                .create()
                .inject(this);
        mViewModel.init(docInterniSetupDTO);
        mViewModel.setListeners(this);
        mBindings.setView(this);
        mBindings.setViewmodel(mViewModel);

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


        mBindings.positiveBtn.setOnClickListener(view -> {
            if (this.isInputValid()) {
                getDialog().dismiss();
            }
        });


        return mBindings.getRoot();
    }

    private void initView() {
        initArrayAdapters();
        initBindables();

        if (selectedDtip != null) {
            codDtip.set(selectedDtip.getLabel());
        }
        if (selectedGrp != null) {
            codMgrp.set(selectedGrp.getLabel());
        }
        if (selectedAnag != null) {
            codAnag.set(selectedAnag.getLabel());
        }
        if (selectedDataDoc != null) {
            dataDoc.set(selectedDataDoc);
        }
        if (selectedNumDoc != null) {
            numDoc.set(selectedNumDoc);
        }
        if (selectedNote != null) {
            note.set(selectedNote);
        }
    }

    private boolean isInputValid() {
        if (this.mViewModel.getSelectedTipoDoc() == null) {
            mBindings.inputCodDtip.setErrorEnabled(true);
            mBindings.inputCodDtip.setError("Seleziona un tipo documento");
            return false;
        }

        if (this.mViewModel.requiresFornitore() && this.mViewModel.getSelectedFornitore() == null) {
            mBindings.inputCodAnagForn.setErrorEnabled(true);
            mBindings.inputCodAnagForn.setError("Seleziona un fornitore/destinatario");
            return false;
        }

        if (this.mViewModel.requiresDocData() && this.mViewModel.getDataDoc() == null){
            mBindings.inputDataDoc.setError("Seleziona la data del documento");
            return false;
        }

        if (this.mViewModel.requiresDocData() && (this.mViewModel.getNumDoc() == null || this.mViewModel.getNumDoc().isEmpty() )){
            mBindings.inputNumDoc.setError("Seleziona il numero del documento");
            return false;
        }

        if (this.mViewModel.requiresNote() && (this.mViewModel.getNote() == null || this.mViewModel.getNote().isEmpty() )){
            mBindings.inputNoteLayout.setErrorEnabled(true);
            mBindings.inputNoteLayout.setError("Specifica delle note per il documento");
            return false;
        }

        return true;
    }

    private void initArrayAdapters() {

        arrayAdapterCodDtips = new ArrayAdapter<>(mCurrentContext, R.layout.dialog_select_doc_info__single_item);
        arrayAdapterCodDtips.addAll(mViewModel.getAvailableCodDtips());
        mBindings.filledExposedDropdownCodDtips.setAdapter(arrayAdapterCodDtips);

        arrayAdapterCodMgrps = new ArrayAdapter<>(mCurrentContext, R.layout.dialog_select_doc_info__single_item);
        arrayAdapterCodMgrps.addAll(mViewModel.getAvailableCodMgrps());
        mBindings.filledExposedDropdownCodMgrps.setAdapter(arrayAdapterCodMgrps);

        arrayAdapterCodAnags = new ArrayAdapter<>(mCurrentContext, R.layout.dialog_select_doc_info__single_item);
        arrayAdapterCodAnags.addAll(mViewModel.getAvailableFornitori());
        mBindings.filledExposedDropdownCodAnagList.setAdapter(arrayAdapterCodAnags);

        arrayAdapterNote = new ArrayAdapter<>(mCurrentContext, R.layout.dialog_select_doc_info__single_item);
        arrayAdapterNote.addAll(mViewModel.getAdditionalNotes());
        mBindings.filledExposedDropdownNote.setAdapter(arrayAdapterNote);
    }

    private void initBindables() {
        BindableString.registerListener(codDtip, codDtip -> {
            mViewModel.setCodDtip(codDtip);
            mBindings.inputCodAnagForn.setVisibility(mViewModel.requiresFornitore() ? View.VISIBLE : View.GONE);
            mBindings.inputDataDocLayout.setVisibility(mViewModel.requiresDocData() ? View.VISIBLE : View.GONE);
            mBindings.inputNumDocLayout.setVisibility(mViewModel.requiresDocData() ? View.VISIBLE : View.GONE);
            mBindings.inputNoteLayout.setVisibility(mViewModel.requiresNote() ? View.VISIBLE : View.GONE);
        });
        BindableString.registerListener(codMgrp, mViewModel::setCodMgrp);
        BindableString.registerListener(codAnag, mViewModel::setCodAnag);
        BindableString.registerListener(numDoc, mViewModel::setNumDoc);
        BindableString.registerListener(note, mViewModel::setNote);
        UtilityObservable.addPropertyChanged(this.dataDoc, (value) -> {
            this.mViewModel.setDataDoc(value);
        });
    }


    @Override
    public void onDocTypeSelected() {
        arrayAdapterCodAnags.clear();
        if (mViewModel.getSelectedFornitore() != null && !mViewModel.getAvailableFornitori().contains(mViewModel.getSelectedFornitore().getLabel())) {
            codAnag.set("");
        }
        if (mViewModel.getNote() != null && ! mViewModel.requiresNote()){
            mViewModel.setNote(null);
        }
        arrayAdapterCodAnags.addAll(mViewModel.getAvailableFornitori());
    }
}
