package it.integry.integrywmsnative.view.dialogs;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

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

import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.databinding.DialogAskActionEditDeleteBinding;

public class DialogAskActionView extends BaseDialogFragment {

    private final String mTitle;
    private final String mSubtitle;

    private final Runnable mOnEditSelected;
    private final Runnable mOnDeleteSelected;
    private boolean runOnDismissAction = true;
    private final Runnable mOnDismiss;


    public static DialogAskActionView newInstance(String title, String subtitle, Runnable onEdit, Runnable onDelete, Runnable onDismiss) {
        return new DialogAskActionView(title, subtitle, onEdit, onDelete, onDismiss);
    }

    public static DialogAskActionView newInstance(String title, String subtitle, Runnable onEdit, Runnable onDelete) {
        return newInstance(title, subtitle, onEdit, onDelete, null);
    }

    private DialogAskActionView(String title, String subTitle, Runnable onEditSelected, Runnable onDeleteSelected, Runnable onDismiss) {
        super();

        mTitle = title;
        mSubtitle = subTitle;

        mOnEditSelected = onEditSelected;
        mOnDeleteSelected = onDeleteSelected;
        mOnDismiss = onDismiss;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        DialogAskActionEditDeleteBinding mBinding = DialogAskActionEditDeleteBinding.inflate(LayoutInflater.from(requireContext()), null, false);
        mBinding.setLifecycleOwner(this);
        mBinding.setViewmodel(this);

        var alertDialogBuilder = new MaterialAlertDialogBuilder(requireContext())
                .setView(mBinding.getRoot());

        mBinding.bottomSheetActionsTitle.setText(mTitle);
        mBinding.bottomSheetActionsSubtitle.setText(mSubtitle);

        return alertDialogBuilder.create();
    }

    public void onEdit() {
        runOnDismissAction = false;
        dismiss();
        mOnEditSelected.run();
    }

    public void onDelete() {
        runOnDismissAction = false;
        dismiss();
        mOnDeleteSelected.run();
    }

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

