package it.integry.integrywmsnative.view.dialogs;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

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

import javax.inject.Singleton;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.databinding.DialogProgressBinding;

@Singleton
public class DialogProgressView extends DialogFragment {

    private DialogProgressBinding mBindings;

    private String title;
    private String subtitle;
    private boolean indeterminateProgress;

    public static DialogProgressView newInstance(String title, String subtitle, boolean indeterminate) {
        return new DialogProgressView(title, subtitle, indeterminate);
    }

    public static DialogProgressView newInstance() {
        return newInstance(null, null, true);
    }

    public DialogProgressView(String title, String subtitle, boolean indeterminate) {
        this.setTitle(title);
        this.setSubtitle(subtitle);
        this.setIndeterminateProgress(indeterminate);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        mBindings = DialogProgressBinding.inflate(LayoutInflater.from(requireContext()));

        mBindings.setTitle(UtilityString.isNullOrEmpty(title) ? requireContext().getString(R.string.loading) : title);
        if (!UtilityString.isNullOrEmpty(subtitle)) mBindings.setSubtitle(subtitle);

        mBindings.progressBar.setIndeterminate(isIndeterminateProgress());
        if (!isIndeterminateProgress()) mBindings.progressBar.setMax(100);

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

        setCancelable(false);
        return alertDialog;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public boolean isIndeterminateProgress() {
        return indeterminateProgress;
    }

    public DialogProgressView setIndeterminateProgress(boolean indeterminateProgress) {
        this.indeterminateProgress = indeterminateProgress;
        return this;
    }

    public void setProgress(int progress) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mBindings.progressBar.setProgress(progress, true);
        }
    }
}
