var subTable = null;

// Create subscription table
function initSubscriptionTable() {
    subTable = $("#subTable").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 mt-0" />',
                data: null,
                orderable: false,
                className: "text-center",
                render: function() {
                    return '<input type="checkbox" class="form-check-input table-select-row mt-0" />'
                }
            },
            { title: "Name", data: "name" },
            { title: "URL", data: "url" },
            { title: "Channels", data: "channels_count" },
            { title: "Created", data: "creation_datetime" },
            {
                title: "Notes",
                data: "extra_notes",
                orderable: false,
                className: "text-center",
                render: function(data, type) {
                    return `<i class="bi bi-chat-left-text" title="${data}"></i>`
                }
            },
            { 
                title: "Active",
                data: "active",
                orderable: false,
                className: "text-center",
                render: function(data, type) {
                    return `<input type="checkbox" class="form-check-input mt-0" ${data ? "checked" : ""} />`
                }
            }
        ]
    });

    // subTable.rows.add([
    //     {
    //         name: "BBC News",
    //         url: "https://feeds.bbci.co.uk/news/rss.xml",
    //         channels_count: 3,
    //         created: "13-03-2024",
    //         notes: "No Description",
    //         active: true
    //     },
    //     {
    //         name: "BBC News - Entertainment",
    //         url: "https://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml",
    //         channels_count: 1,
    //         created: "22-03-2024",
    //         notes: "No Description",
    //         active: true
    //     },
    //     {
    //         name: "BBC News - Politics",
    //         url: "https://feeds.bbci.co.uk/news/politics/rss.xml",
    //         channels_count: 5,
    //         created: "16-03-2024",
    //         notes: "No Description",
    //         active: true
    //     },
    //     {
    //         name: "BBC News - North America",
    //         url: "https://feeds.bbci.co.uk/news/north_america/rss.xml",
    //         channels_count: 2,
    //         created: "04-04-2024",
    //         notes: "No Description",
    //         active: true
    //     }
    // ]).draw(false);
}

// Determine and apply the state of the 'select all' checkbox
// indeterminate, checked or neither
function determineSelectAllState() {
    var selectedRowsCount = subTable.rows(".selected").data().toArray().length;
        allRowsCount = subTable.rows().data().toArray().length;

        selectAllCheckbox = $("#subTable thead .table-select-all");

        checked = selectedRowsCount === allRowsCount;
        indeterminate = !checked && selectedRowsCount > 0;

    selectAllCheckbox.prop("checked", checked);
    selectAllCheckbox.prop("indeterminate", indeterminate);
}

// Select a row via checkbox
$("#subTable").on("change", "tbody tr .table-select-row", function() {

    var selected = $(this).prop("checked");
        rowIndex = $(this).closest("tr").index();
        row = subTable.row(rowIndex);

    if (selected) row.select();
    else row.deselect();

    determineSelectAllState();
});

// Select all rows checkbox
$("#subTable").on("change", "thead .table-select-all", function() {
    var selected = $(this).prop("checked");
    $('#subTable tbody tr').each(function(rowIndex) {
        var row = subTable.row(rowIndex)

        if (selected) row.select();
        else row.deselect();

        $(this).find('.table-select-row').prop("checked", selected);
    });

    determineSelectAllState();
});

// Alert the number of selected rows
$("#tableButton").on("click", function() {
    var selectedRows = subTable.rows({ selected: true }).data(false).toArray();
    alert(selectedRows.length + " row(s) are selected");
});

// Open new subscription modal
$("#tableAddRowBtn").on("click", function() {
    $("#subFormModal").modal("show");
});

$("#subForm").on("submit", async function(event) {
    event.preventDefault();

    var name = $("#subName").val();
        url = $("#subUrl").val();
        guildId = $("#subGuildId").val();
        extraNotes = $("#subExtraNotes").val();

    var subPrimaryKey = await registerNewSubscription(name, url, guildId, extraNotes);
    if (subPrimaryKey)
        showToast("success", "subscription created", "created with ID: " + subPrimaryKey);

    $("#subFormModal").modal("hide");
});

async function registerNewSubscription(name, url, guildId, extraNotes) {
    var formData = new FormData();
    formData.append("name", name);
    formData.append("url", url);
    formData.append("guild_id", guildId);
    formData.append("extra_notes", extraNotes);
    formData.append("active", true);

    try { response = await newSubscription(formData); }
    catch (err) {
        // alert(JSON.stringify(err))
        showToast("danger", "Subscription Error", err.responseText, 18000);
        return false;
    }

    return response.id;
}

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

async function loadSubscriptions(guildId) {

    if (!guildId) 
        return;

    clearExistingTableRows();

    try {
        const subscriptions = await getSubscriptions(guildId);
        subTable.rows.add(subscriptions.results).draw(false);
    }
    catch (err) {
        console.error(JSON.stringify(error, null, 4));
        showToast("danger", `Error Loading Subscriptions: HTTP ${error.status}`, error.responseJSON.message, 15000);
    }
}

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