
const validateBootstrapStyle = style => {
    if (!["danger", "success", "warning", "info", "primary", "secondary"].includes(style)) {
        throw new Error(`${style} is not a valid style`);
    }
    return true;
}


const arrayToHtmlList = (array, bold=false) => {
    $ul = $("<ul>").addClass("mb-0");
    
    array.forEach(item => {
        let $li = $("<li>");
        $ul.append(bold ? $li.append($("<b>").text(item)) : $li.text(item));
    });
    
    return $ul;
}


const createModal = async (options = {}) => {
    let $modal = $("#customModal");

    let defaults = {
        title: "Modal Title",
        texts: [
            {
                content: "This is a modal",
                html: false
            }
        ],
        buttons: [
            {
                text: "Okay",
                className: "btn-primary",
                iconClass: "",
                tabIndex: 2,
                closeModal: true,
                onClick: null
            }
        ]
    };

    let settings = { ...defaults, ...options };

    $modal.find(".modal-title").text(settings.title);

    // Texts
    let $body = $modal.find(".modal-body").empty();

    settings.texts.forEach((text, idx) => {
        if (text.html) {
            $body.append(text.content);
            return;
        }

        let $para = $("<p>", {
            text: text.content,
            class: idx + 1 === settings.texts.length ? "mb-0" : ""
        });
        $body.append($para);
    });

    // Buttons
    let $footer = $modal.find(".modal-footer").empty();

    settings.buttons.forEach(button => {
        let $btn = $("<button>", {
            type: "button",
            class: "btn rounded-1 " + button.className,
            tabIndex: button.tabIndex,
            html: button.iconClass ?`<i class="${button.iconClass} ${button.text ? "me-2" : ""}"></i>${button.text ? button.text : ""}` : button.text
        });

        $btn.on("click", async () => {
            if (button.onClick) await button.onClick();
            if (button.closeModal) $modal.modal("hide");
        });

        $footer.append($btn);
    });

    $modal.modal("show");
}
