const contentTableId = "#contentTable";


// region Init Module

function initContentModule() {
    initializeDataTable(
        contentTableId,
        [
            {
                title: "Subscription",
                data: "subscription",
            },
            {
                title: "Item ID",
                data: "item_id",
                className: "col-name"
            },
            {
                title: "Item GUID",
                data: "item_guid",
                className: "col-name"
            },
            {
                title: "Title",
                data: "item_title",
                className: "col-name"
            },
            {
                title: "URL",
                data: "item_url",
                className: "col-url"
            },
            {
                title: "Content Hash",
                data: "item_content_hash",
                className: "col-name"
            },
            {
                title: "Blocked",
                data: "blocked",
                className: "col-icon",
                render: renderBooleanColumn
            }
        ]
    );
}


// region Load Data

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

$(contentTableId).on("doDataLoad", async function() {
    await loadContentData();
})

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

    setTableFilter(contentTableId, "subscription__server", selectedServer.id);
    await loadTableData(contentTableId, "/api/content/", "GET");
}

// region Delete Data

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

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

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

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