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

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.List;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.model.MtbAart;
import it.integry.integrywmsnative.databinding.DialogChooseArtFromListaArtBinding;
import it.integry.integrywmsnative.ui.SimpleDividerItemDecoration;

public class DialogChooseArtFromListaArtsView extends DialogFragment {


    private final List<MtbAart> mListaArts;
    private final RunnableArgs<MtbAart> mOnItemChoosed;


    public DialogChooseArtFromListaArtsView(List<MtbAart> listaArts, RunnableArgs<MtbAart> onItemChoosed) {
        super();
        this.mListaArts = listaArts;
        this.mOnItemChoosed = onItemChoosed;
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        var binding = DialogChooseArtFromListaArtBinding.inflate(LayoutInflater.from(requireContext()));

        initRecyclerView(binding, mListaArts);

        var alertDialog = new MaterialAlertDialogBuilder(requireContext())
                .setView(binding.getRoot())
                .setCancelable(false)
                .create();

        alertDialog.setCanceledOnTouchOutside(false);
        return alertDialog;
    }

    private void initRecyclerView(DialogChooseArtFromListaArtBinding binding, List<MtbAart> dataset) {
        binding.dialogChooseArtFromListaArtMainList.setNestedScrollingEnabled(false);
        binding.dialogChooseArtFromListaArtMainList.setHasFixedSize(true);
        binding.dialogChooseArtFromListaArtMainList.setLayoutManager(new LinearLayoutManager(requireContext()));

        SimpleDividerItemDecoration itemDecorator = new SimpleDividerItemDecoration(requireContext(), SimpleDividerItemDecoration.VERTICAL);
        itemDecorator.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.divider));
        binding.dialogChooseArtFromListaArtMainList.addItemDecoration(itemDecorator);

        DialogChooseArtFromListaArtsAdapter mCurrentAdapter = new DialogChooseArtFromListaArtsAdapter(requireContext(), dataset,
                ((item, position) -> {
                    if (mOnItemChoosed != null) {
                        mOnItemChoosed.run(item);
                    }

                    dismiss();
                }));
        binding.dialogChooseArtFromListaArtMainList.setAdapter(mCurrentAdapter);
    }

}
