var contentTable;

async function initContentTable() {
    await initTable("#contentTabPane", "contentTable", loadContent);

    contentTable = $("#contentTable").DataTable({
        info: false,
        paging: false,
        searching: false,
        autoWidth: false,
        order: [],
        select: {
            style: "multi+shift",
            selector: 'th:first-child input[type="checkbox"]'
        },
        columnDefs: [
            { orderable: false, targets: "no-sort" },
            {
                targets: 0,
                checkboxes: { selectRow: true }
            }
        ],
        columns: [
            {
                // Select row checkbox column
                title: '<input type="checkbox" class="form-check-input table-select-all" />',
                data: null,
                orderable: false,
                className: "text-center col-switch-width",
                render: function() {
                    return '<input type="checkbox" class="form-check-input table-select-row" />'
                }
            },
            { data: "id", visible: false },
            {
                title: "GUID",
                data: "guid",
                className: "text-truncate mw-10rem",
            },
            {
                title: "Name",
                data: "title",
                className: "text-truncate",
                render: function(data, type, row) {
                    return `<a href="${row.url}" class="text-decoration-none" target="_blank">${data}</a>`
                }
            },
            {
                title: "Subscription",
                data: "subscription.name",
                className: "text-nowrap",
                render: function(data, type, row) {
                    return `<a href="#" onclick="goToSubscription(${row.subscription.id})" class="text-decoration-none">${data}</a>`
                }
            },
            {
                title: "Blocked",
                data: "blocked",
                className: "text-center col-1",
                render: function(data) {
                    return data ? `<i class="bi bi-check-lg text-success"></i>` : ""
                }
            },
            {
                title: "Channel",
                data: "channel_id",
                className: "text-start content-channel-id",
                render: function(data) {
                    return $("<span>").text(data)[0];
                }
            },
            {
                title: "Created",
                data: "creation_datetime",
                className: "text-nowrap",
                render: function(data, type) {
                    // return new Date(data).toISOString().split("T")[0];
                    let dateTime = new Date(data);
                    let dateTimeString = formatDate(dateTime);
                    return $(`
                    <span data-bs-trigger="hover focus"
                    data-bs-html="true"
                    data-bs-custom-class="text-center"
                    data-bs-toggle="popover"
                    data-bs-content="${dateTimeString}">
                    ${dateTime.toISOString().split("T")[0]}
                    </span>
                    `).popover()[0];
                }
            },
            {
                orderable: false,
                className: "p-0",
                render: function(data, type, row) {
                    return `<div class="h-100" style="background-color: #${row.subscription.embed_colour}; width: .25rem;">&nbsp;</div>`
                }
            }
        ]
    });

    bindTableCheckboxes("#contentTable", contentTable, "#deleteSelectedContentBtn");
}

function handleDiscordChannelNames() {
    let interval = setInterval(function() {

        if (!discordChannels.length)
            return;

        $("#contentTable tr td.content-channel-id").each(function() {
            console.debug("row")
            let tracked = contentTable.row($(this).closest("tr")).data();
                channel = discordChannels.find(item => item.value === tracked.channel_id);

            if (!channel)
                return;

            console.debug("inserting")
            $(this).text("").append(
                $("<a>")
                .attr("href", `https://discord.com/channels/${getCurrentlyActiveServer().guild_id}/${channel.value}/${tracked.message_id}`)
                .attr("target", "_blank")
                .addClass("text-decoration-none")
                .text(channel.text)
            );
        });

        // $(".replace-discord-channel-id-with-name").each(function() {
        //     let displayChannel = discordChannels.find(channel => channel.value == $(this).text());
        //     if (displayChannel) {
        //         $(this).text("").append(
        //             $("<a>")
        //             .attr("href", `https://discord.com/channels/${getCurrentlyActiveServer().guild_id}/${displayChannel.value}`)
        //             .attr("target", "_blank")
        //             .addClass("text-decoration-none")
        //             .text(displayChannel.text)
        //         );
        //     }
        // });


    }, 600);
}

async function goToSubscription(subId) {
    $("#subscriptionsTab").click();
    await showEditSubModal(subId);
}

$("#deleteSelectedContentBtn").on("click", async function() {

    var rows = contentTable.rows(".selected").data();
    $.each(rows, async function() {
        await deleteTrackedContent(this.id);
        showToast("danger", "Deleted Tracked Content", "It can now appear be sent again. Content ID: " + this.id);
    });

    setTimeout(async () => {
        await loadContent(getCurrentlyActiveServer().guild_id);
    }, 600)
});

function clearExistingContentRows() {
    $("#contentTable thead .table-select-all").prop("checked", false).prop("indeterminate", false);
    contentTable.clear().draw(false);
}

$("#refreshContentBtn").on("click", async function() {
    loadContent(getCurrentlyActiveServer().guild_id);
});

async function loadContent(guildId, page=1, pageSize=null) {

    if (!guildId)
        return;

    if (!pageSize)
        pageSize = $("#contentTablePageSize").val();

    $("#deleteSelectedContentBtn").prop("disabled", true);
    clearExistingContentRows();

    try {
        const content = await getTrackedContent(guildId, null, page, pageSize);
        contentTable.rows.add(content.results).draw(false);

        updateTablePagination("#contentTabPane .table-pagination", page, pageSize, content.count, content.next, content.previous);
        updateTablePaginationInfo("#contentTabPane .table-page-info", content.results.length, content.count);

        $("#contentTable thead .table-select-all").prop("disabled", content.results.length === 0);
    }
    catch (err) {
        console.error(JSON.stringify(err, null, 4));
        showToast("danger", `Error loading Tracked Content: HTTP ${err.status}`, err.responseJSON.message, 15000);
    }
}

$(document).on("selectedServerChange", async function() {
    const activeServer = getCurrentlyActiveServer();
    await loadContent(activeServer.guild_id);
});
