
const subTableId = "#subTable";
const subModalId = "#subFormModal";


// region Init Module

function initSubscriptionsModule() {
    initializeDataTable(
        subTableId,
        [
            {
                title: "Name",
                data: "name",
                className: "col-name",
                render: renderEditColumn
            },
            {
                title: "URL",
                data: "url",
                className: "col-url",
                render: url => renderAnchorColumn(url, url)
            },
            {
                title: "Channels",
                data: "channels_detail",
                className: "col-icon",
                render: data => renderPopoverBadgesColumn(data.map(item => `#${item.name}`), "bi-hash")
            },
            {
                title: "Filters",
                data: "filters_detail",
                className: "col-icon",
                render: data => renderPopoverBadgesColumn(data.map(item => item.name), "bi-funnel")
            },
            {
                title: "Rules",
                data: "unique_rules_detail",
                className: "col-icon",
                render: data => renderPopoverBadgesColumn(data.map(item => item.name), "bi-vr")
            },
            {
                title: "Style",
                data: "message_style_detail",
                className: "col-hex",
                render: renderLinkToStyleColumn
            },
            {
                title: "Created At",
                data: "created_at",
                className: "col-date",
                render: function(data, type) {
                    let dateTime = new Date(data);
                    return $(`
                        <span data-bs-trigger="hover focus"
                            data-bs-html="true"
                            data-bs-custom-class="text-center"
                            data-bs-toggle="popover"
                            data-bs-content="${formatStringDate(dateTime, "%a, %D %B, %Y<br>%H:%M:%S")}">
                            ${formatStringDate(dateTime, "%D, %b %Y")}
                        </span>
                    `).popover()[0];
                }
            },
            {
                title: "Enabled",
                data: "active",
                className: "col-switch text-center form-switch",
                render: function(data, type) {
                    return `<input type="checkbox" class="sub-toggle-active form-check-input ms-0" ${data ? "checked" : ""} />`
                }
            }
        ]
    );
}


// region Load Data

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

$(subTableId).on("doDataLoad", async function() {
    await loadSubscriptionData();
})

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

    setTableFilter(subTableId, "server", selectedServer.id);
    await loadTableData(subTableId, `/api/subscriptions/`, "GET");
}


// region Table Switches

$(subTableId).on("change", ".sub-toggle-active", async function() {

    // Temporarily disable all switches to prevent spam.
    $(subTableId).find(".sub-toggle-active").prop("disabled", true);
    setTimeout(() => { $(subTableId).find(".sub-toggle-active").prop("disabled", false); }, 800);

    let active = $(this).prop("checked");
    let id = $(subTableId).DataTable().row($(this).closest("tr")).data().id;
    let sub = await ajaxRequest(`/api/subscriptions/${id}/`, "GET");
    sub.active = active;
    let formData = objectToFormData(sub);
    await ajaxRequest(`/api/subscriptions/${id}/`, "PUT", formData);
});


// region Table Delete Buttons

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

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

    const deleteSubscription = async () => {
        await ajaxRequest(`/api/subscriptions/${subscription.id}/`, "DELETE");
        setTimeout(() => { $(subTableId).trigger("doDataLoad") }, 600);
    }

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

getTableFiltersComponent(subTableId).find(".table-del-btn").on("click", async function() {
    const rows = getSelectedTableRows(subTableId);
    const names = rows.map(row => row.name);
    const isMany = names.length > 1;

    const deleteSubscriptions = () => {
        rows.forEach(async row => {
            await ajaxRequest(`/api/subscriptions/${row.id}/`, "DELETE");
        });

        setTimeout(() => { $(subTableId).trigger("doDataLoad") }, 600);
    }

    createModal({
        title: `Delete ${isMany ? "Many Subscriptions" : "Subscription"}`,
        texts: [
            {
                content: `<p>Do you wish to permanently delete ${isMany ? "these" : "these"} subscription${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: deleteSubscriptions
            },
            {
                className: "btn-secondary px-4",
                iconClass: "bi-arrow-return-right",
                closeModal: true
            }
        ]
    });
});


// region New/Edit Modal

$(subTableId).closest('.js-tableBody').siblings('.js-tableFilters').on("click", ".table-new-btn", async function() {
    await openSubModal(-1);
});

$(subTableId).on("click", ".edit-modal", async function() {
    const id = $(subTableId).DataTable().row($(this).closest("tr")).data().id;
    await openSubModal(id);
})

async function openSubModal(id) {
    await loadChannelOptions();
    await openDataModal(subModalId, id, id !== -1 ? `/api/subscriptions/${id}/`: null);
}

$(subModalId).on("submit", async function(event) {
    event.preventDefault();
    await onModalSubmit(
        $(subModalId),
        $(subTableId),
        "/api/subscriptions/"
    );
});


// region Load Modal Options

$(document).on("selectedServerChange", async function() {
    await loadSubModalOptions(
        $(subModalId).find('[data-field="message_style"]'),
        `/api/message-styles/?server=${selectedServer.id}`
    );
    await loadSubModalOptions(
        $(subModalId).find('[data-field="filters"]'),
        `/api/filters/?server=${selectedServer.id}`
    );
    
});

$(document).ready(async function() {
    await loadSubModalOptions(
        $(subModalId).find('[data-field="unique_rules"]'),
        "/api/unique-content-rules/"
    );
})

async function loadSubModalOptions($input, url) {
    // Disable and clear input
    $input.val("").change();
    $input.prop("disabled", true);

    // Delete existing options
    $input.find("option").each(function() {
        if ($(this).val()) {
            $(this).remove();
        }
    });

    // Load new values
    const data = await ajaxRequest(url, "GET");
    data.results.forEach(item => {
        $input.append($(
            "<option>",
            {text: item.name, value: item.id}
        ));
    });

    // Re-enable input
    $input.prop("disabled", false);
}

// Channel options aren't loaded from an API, like other options.
async function loadChannelOptions() {
    $input = $(subModalId).find('[data-field="channels"]');

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

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

    const data = await loadedChannels(selectedServer.id);
    data.forEach(item => {
        $input.append($(
            "<option>",
            {text: `#${item.name}`, value: item.id}
        ));
    })

    $input.prop("disabled", false);
}


// region Open Sub Style

$(subTableId).on("click", ".js-openSubStyle", async event => {
    const subTable = $(subTableId).DataTable();
    const row = subTable.row($(event.currentTarget).closest("tr"));
    const styleId = row.data().message_style

    // Open styles tab and styles modal
    $("#stylesTab").click();
    await openDataModal(styleModalId, styleId, `/api/message-styles/${styleId}/`);
});
