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

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.MutableLiveData;

import com.annimon.stream.Stream;
import com.ravikoradiya.liveadapter.LiveAdapter;

import java.util.List;

import it.integry.integrywmsnative.BR;
import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_store.db.entity.SqlMtbColr;
import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.databinding.DialogChooseRowFromListaDocRowsLayoutBinding;
import it.integry.integrywmsnative.gest.contab_doc_interni.dto.DialogChooseRowFromListaDocRowsListModel;
import kotlin.Unit;

public class DialogSelectDocRowsView extends BaseDialogFragment {

    private final RunnableArgs<SqlMtbColr> onRowSelected;
    private final List<SqlMtbColr> listArts;
    private final MutableLiveData<List<DialogChooseRowFromListaDocRowsListModel>> listModels = new MutableLiveData<>();
    private DialogChooseRowFromListaDocRowsLayoutBinding binding;
    public MutableLiveData<SqlMtbColr> selectedRow = new MutableLiveData<>();

    public static DialogSelectDocRowsView newInstance(
            List<SqlMtbColr> listArts,
            RunnableArgs<SqlMtbColr> onDismiss
    ) {
        return new DialogSelectDocRowsView(listArts, onDismiss);
    }


    private DialogSelectDocRowsView(List<SqlMtbColr> listArts, RunnableArgs<SqlMtbColr> onDismiss) {
        super();
        this.onRowSelected = onDismiss;
        this.listArts = listArts;
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (onRowSelected != null) onRowSelected.run(this.selectedRow.getValue());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.dialog_choose_row_from_lista_doc_rows_layout, container, false);
        binding.setLifecycleOwner(this);
        MainApplication
                .appComponent
                .dialogSelectDocRowsComponent()
                .create()
                .inject(this);
        binding.setView(this);

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


        binding.positiveButton.setOnClickListener(view -> {
            getDialog().dismiss();
        });

        binding.negativeButton.setOnClickListener(view -> {
            this.selectedRow.setValue(null);
            getDialog().dismiss();
        });


        this.onLoadingEnded();
        return binding.getRoot();
    }

    private void refreshList() {
        var list = Stream.of(this.listArts).map(row -> {
            DialogChooseRowFromListaDocRowsListModel model = new DialogChooseRowFromListaDocRowsListModel();
            model.setCodMart(row.getCodMart());
            model.setBarcode(row.getCodMart());
            model.setOriginalModel(row);
            model.setNew(row.getId() < 1);
            model.setDescrizione(row.getDescrizione());
            model.setQtaOrdReadable(row.getQtaCol() + "\n" + row.getUntMis());
            model.getChecked().addOnPropertyChangedCallback(() -> {
                this.checkRow(row, model.getChecked().get());
            });
            return model;
        }).toList();
        this.listModels.postValue(list);

    }

    private void checkRow(SqlMtbColr row, boolean checked) {
        if (checked) {
            this.selectedRow.setValue(row);
            var models = this.listModels.getValue();
            if (models != null && !models.isEmpty()) {
                Stream.of(models).filter(model -> model.getOriginalModel().getId() != row.getId()).forEach(model -> {
                    model.getChecked().set(false);
                });
            }
        } else {
            var selectedRow = this.selectedRow.getValue();
            if (selectedRow != null && selectedRow.getId() == row.getId()) {
                this.selectedRow.setValue(null);
            }
        }
    }

    private void initView() {
        initArrayAdapters();
    }

    private void initArrayAdapters() {

        new LiveAdapter(listModels, getViewLifecycleOwner(), BR.row)
                .map(DialogChooseRowFromListaDocRowsListModel.class, R.layout.dialog_choose_row_from_lista_doc_rows__item_model)
                .onNoData(noData -> {
                            binding.emptyView.setVisibility(noData ? View.VISIBLE : View.GONE);
                            return Unit.INSTANCE;
                        }
                ).into(binding.listaDocRows);

    }

}
