const styleTableId = "#styleTable";
const styleModalId = "#styleFormModal";


// region Init Module

function initMessageStylesModule() {
    initializeDataTable(
        styleTableId,
        [
            {
                title: "Name",
                data: "name",
                className: "col-name",
                render: (name, type, style) => {
                    const elem = renderEditColumn(name);
                    return style.auto_created ?
                        $(elem).removeClass("edit-modal").addClass("disabled").attr("role", null)[0]
                        : elem;
                }
            },
            {
                title: "Embed",
                data: "is_embed",
                className: "col-icon",
                render: renderBooleanColumn
            },
            {
                title: "Colour",
                data: "colour",
                className: "col-hex",
                render: renderHexColourColumn
            },
            {
                title: "Hyperlinked",
                data: "is_hyperlinked",
                className: "col-icon-wide",
                render: renderBooleanColumn
            },
            {
                title: "Authored",
                data: "show_author",
                className: "col-icon-wide",
                render: renderBooleanColumn
            },
            {
                title: "Timestamped",
                data: "show_timestamp",
                className: "col-icon-wide",
                render: renderBooleanColumn
            },
            {
                title: "Images",
                data: "show_images",
                className: "col-icon",
                render: renderBooleanColumn
            },
            {   
                title: "Fetch Images",
                data: "fetch_images",
                className: "col-icon-wide",
                render: renderBooleanColumn
            },
            {
                title: "Title Mutator",
                data: "title_mutator_detail",
                render: (data, type, row) => renderMutatorColumn(row.title_mutator_detail)
            },
            {
                title: "Description Mutator",
                data: "description_mutator_detail",
                render: (data, type, row) => renderMutatorColumn(row.description_mutator_detail)
            },
            {
                title: "Editable",
                data: "auto_created",
                className: "text-center",
                render: function(data) {
                    const icon = renderBooleanColumn(!data);
                    if (!data) {
                        return icon;
                    }

                    return $(`
                        <span data-bs-trigger="hover focus"
                            data-bs-custom-class="text-center"
                            data-bs-toggle="popover"
                            data-bs-content="This style was created internally, and cannot be altered.">
                            ${icon}
                        </span>
                    `).popover()[0];
                }
            }
        ]
    );
};


// region Load Data

$(document).on("selectedServerChange", async function() {
    await loadMessageStyleData();
});

$(document).on("doDataLoad", async function() {
    await loadMessageStyleData();
});

async function loadMessageStyleData() {
    if (!selectedServer) {
        return;
    }

    setTableFilter(styleTableId, "server", selectedServer.id);
    await loadTableData(styleTableId, "/api/message-styles/", "GET");
}

// region Table Delete Btns

$(styleModalId).find(".modal-del-btn").on("click", async function() {
    $(styleModalId).modal("hide");

    const id = parseInt($(styleModalId).data("primary-key"));
    const style = $(styleTableId).DataTable().row((idx, row) => { return row.id === id }).data();
    const name = sanitise(style.name);

    const deleteStyle = async () => {
        await ajaxRequest(`/api/message-styles/${style.id}/`, "DELETE");
        setTimeout(async () => {
            $(styleTableId).trigger("doDataLoad");
            await loadSubModalOptions(
                $(subModalId).find('[data-field="message_style"]'),
                `/api/message-styles/?server=${selectedServer.id}`
            );
        }, 600);
    }

    createModal({
        title: "Delete a Message Style",
        texts: [
            {
                content: `<span>Do you wish to permanently delete <b>${name}</b>?</span>`,
                html: true
            },
            { content: "This action is irreversible, you will lose this filter forever." }
        ],
        buttons: [
            {
                className: "btn-danger me-3",
                iconClass: "bi-trash3",
                closeModal: true,
                onClick: deleteStyle,
            },
            {
                className: "btn-secondary px-4",
                iconClass: "bi-arrow-return-right",
                closeModal: true,
                onClick: async () => $(styleModalId).modal("show")
            }
        ]
    });
});

getTableFiltersComponent(styleTableId).find(".js-tableDeleteBtn").on("click", async function() {
    const rows = getSelectedTableRows(styleTableId);
    const isMany = rows.length > 1;

    for (const row of rows) {
        if (!row.auto_created) {
            continue;
        }

        createModal({
            title: "Cannot Delete Style",
            texts: [
                {
                    content: `<p><b>${sanitise(row.name)}</b> can't be deleted, as it was created by the system.</p>`,
                    html: true
                },
                { content: "System-owned styles cannot be modified or deleted." },
            ],
            buttons: [
                {
                    className: "btn-warning px-4",
                    iconClass: "bi-arrow-return-right",
                    closeModal: true
                }
            ]
        });
        return
    }

    const names = rows.map(row => row.name);

    const deleteStyles = async () => {
        rows.forEach(async row => {
            await ajaxRequest(`/api/message-styles/${row.id}/`, "DELETE");
        });

        setTimeout(async () => {
            $(styleTableId).trigger("doDataLoad");
            await loadSubModalOptions(
                $(subModalId).find('[data-field="message_style"]'),
                `/api/message-styles/?server=${selectedServer.id}`
            );
        }, 600);
    }

    createModal({
        title: `Delete ${isMany ? "Many Message Styles" : "Message Style"}`,
        texts: [
            {
                content: `<p>Do you wish to permanently delete ${isMany ? "these" : "these"} message style${isMany ? "s" : ""}?</p>`,
                html: true
            },
            {
                content: arrayToHtmlList(names, true).prop("outerHTML"),
                html: true
            }
        ],
        buttons: [
            {
                className: "btn-danger me-3",
                iconClass: "bi-trash3",
                closeModal: true,
                onClick: deleteStyles
            },
            {
                className: "btn-secondary px-4",
                iconClass: "bi-arrow-return-right",
                closeModal: true
            }
        ]
    });
});


// region New/Edit Modal

$(styleTableId).closest(".js-tableBody").siblings(".js-tableFilters").on("click", ".js-tableAddBtn", async function() {
    await openDataModal(styleModalId, -1);
});

$(styleTableId).on("click", ".edit-modal", async function() {
    let id = $(styleTableId).DataTable().row($(this).closest("tr")).data().id;
    await openDataModal(styleModalId, id, `/api/message-styles/${id}/`);
});

$(styleModalId).on("submit", async function(event) {
    event.preventDefault();
    onModalSubmit(
        $(styleModalId),
        $(styleTableId),
        "/api/message-styles/"
    ).then(async () => {
        // Reload sub data to reflect style changes
        $(subTableId).trigger("doDataLoad");
        await loadSubModalOptions(
            $(subModalId).find('[data-field="message_style"]'),
            `/api/message-styles/?server=${selectedServer.id}`
        );
    });
});


// region Load Mutator Options

$(document).ready(async function() {
    await loadMutatorOptions();
});

async function loadMutatorOptions() {
    let $inputs = $(styleModalId).find('[data-field="title_mutator"], [data-field="description_mutator"]');

    $inputs.val("").change();
    $inputs.prop("disabled", true);

    $inputs.find("option").each(function() {
        if ($(this).val()) {
            $(this).remove();
        }
    });

    const data = await ajaxRequest("/api/message-mutators/?page_size=25", "GET");
    data.results.forEach(mutator => {
        $inputs.append($(
            "<option>",
            {text: mutator.name, value: mutator.id}
        ));
    });

    $inputs.prop("disabled", false);

    // Re-init the component
    if ($inputs.next('.corbz-select-container').length) {
        $inputs.next('.corbz-select-container').remove();
        $inputs.initCorbzSelect();
    }
}
