function createSubCategory(serverId) {
    var template = $($("#subCategoryTemplate").html());

    template.find(".cat-id").text(serverId);

    var server = getServer(serverId).then(resp => {
        template.find(".cat-icon").attr("src", resp.icon_url);
        template.find(".cat-name").text(resp.name);
    });
    

    return template
}

function createSubscriptionItem(data) {
    var template = $($("#subItemTemplate").html());

    // Store the uuid for later reference
    template.find(".sub-item").attr("data-uuid", data.uuid);

    // Display data
    template.find(".sub-name").text(data.name);
    template.find(".sub-uuid").text(data.uuid);
    template.find(".sub-rss").text(data.rss_url).attr("href", data.rss_url);
    template.find(".sub-img").attr("src", data.image);
    template.find(".sub-channel-count").text(data.targets.split(";").length);

    // Display Sub Description
    if (!data.extra_notes) {
        template.find(".sub-desc").hide();
    } else {
        template.find(".sub-desc").text(data.extra_notes);
    }

    // Display formatted datetime
    var displayDate = new Date(data.creation_datetime).toISOString().slice(0, 10);
    template.find(".sub-datetime").text(displayDate);

    // Provide button functionality
    template.find(".sub-edit").attr("onclick", `subEditModal("${data.uuid}");`);
    template.find(".sub-delete").attr("onclick", `confirmUnsubscribe("${data.uuid}");`);

    // Enable tooltips
    template.find('[data-bs-toggle="tooltip"]').tooltip();

    // Make the switch toggle the active flag
    template.find(".sub-active").prop("checked", data.active).change(function() {

        var formData = new FormData();
        formData.append("active", $(this).prop("checked"));

        patchSubscription(data.uuid, formData).then(function(resp) {
            console.debug("active flag changed successfully");
        })
    });

    return template
}

$(document).ready(function() {
    loadGuilds();
    loadSubscriptions();

    $("#editSubServer").change(function() {
        loadChannels($(this).find("option:selected").attr("value"));
    });
});

function loadGuilds() {
    $.ajax({
        url: "/guilds",
        type: "GET",
        success: function(response) {
            for (i = 1; i < response.length; i++) {
                var guild = response[i];
                $("#editSubServer").append($("<option>", {
                    value: guild.guild_id,
                    text: guild.name
                }));
            }
        },
        error: function(response) {
            alert(JSON.stringify(response, null, 4));
        }
    });
}

function loadChannels(guildID) {
    $("#editSubChannels").empty();
    $("#editSubChannels").val(null);
    $.ajax({
        url: `/channels?guild=${guildID}`,
        type: "GET",
        success: function(response) {
            for (i = 1; i < response.length; i++) {
                var channel = response[i];

                if (channel.type !== 0) {
                    continue
                }

                var selectedChannelIDs;

                try {
                    selectedChannelIDs = $("#editSubChannels").attr("data-current").split(";");
                }
                catch {
                    selectedChannelIDs = [];
                }

                $("#editSubChannels").append($("<option>", {
                    value: channel.id,
                    text: "#" + channel.name,
                    selected: selectedChannelIDs.includes(channel.id.toString())
                }));
            }
        },
        error: function(response) {
            console.error(JSON.stringify(response, null, 4));

            if (response.code == "50001") {
                alert("PYRSS Bot is Missing Access to this Server");
            }
            else {
                alert("unknown error fetching channels " + response.code)
            }
        }
    });
}

function updateSubscriptionCount(difference, overwrite) {
    const beforeChange = overwrite ? 0 : Number($(".subs-count").text());
    $(".subs-count").text(beforeChange + difference);
}

function loadSubscriptions() {
    $("#subscriptionContainer").empty();
    getSubscriptions().then(resp => {
        updateSubscriptionCount(resp.results.length, true);

        var categorisedSubs = {};

        $.each(resp.results, function(index, sub) {
            categorisedSubs[sub.server] = categorisedSubs[sub.server] || [];
            categorisedSubs[sub.server].push(sub);
        });

        console.log(JSON.stringify(categorisedSubs, null, 4))

        $.each(categorisedSubs, function(server, subs) {
            var categoryElem = createSubCategory(server);
            $("#subscriptionContainer").append(categoryElem);

            $.each(subs, function(index, sub) {
                var subElem = createSubscriptionItem(sub);
                categoryElem.find(".sub-container").append(subElem);
            });
        })
    });
}

function confirmUnsubscribe(uuid) {
    var title = $(`.sub-item[data-uuid='${uuid}'] .sub-name`).text();
    $(".del-sub-name").text(title);
    $(".del-sub-uuid").text(uuid);
    $(".del-sub-confirm").attr("onclick", `unsubscribe("${uuid}")`)
    $("#subDeleteModal").modal("show");
}

function unsubscribe(uuid) {
    var subElem = $(`#subscriptionContainer .sub-item[data-uuid="${uuid}"]`);
    subElem.find("button").prop("disabled", true);

    deleteSubscription(uuid).then(resp => {
        subElem.parent().remove();
        updateSubscriptionCount(-1);
        $("#subDeleteModal").modal("hide");
    });
}


function subEditModal(uuid) {

    var modal = $("#subEditModal");

    modal.find("input").val(null);
    modal.find("textarea").val(null);
    modal.find("select").val("");
    $("#editSubChannels").empty();
    $("#subEditForm").removeClass("was-validated");
    $("#navDetailsTab").click();

    if (uuid === -1) {
        modal.find(".modal-title").text("New Subscription");
    }
    else {
        modal.find(".modal-title").text("Edit Subscription");

        getSubscription(uuid).then(resp => {
            // alert(JSON.stringify(resp, null, 4));
            $("#editSubName").val(resp.name);
            $("#editSubURL").val(resp.rss_url);
            $("#editSubServer").val(String(resp.server)).trigger("change");
            $("#editSubChannels").attr("data-current", resp.targets);
            $("#editSubNotes").val(resp.extra_notes);
        });
    }

    $("#subEditModal").attr("data-uuid", uuid);
    $("#subEditModal").modal("show");
}

function submitSubEditModal() {
    // Validation
    var form = $("#subEditForm");
    if (!form[0].checkValidity()) {
        form.addClass("was-validated");
        return;
    }

    const uuid = $("#subEditModal").attr("data-uuid");
    const subName = $("#editSubName").val();

    var formData = new FormData();
    formData.append("uuid", uuid);
    formData.append("name", subName);
    formData.append("rss_url", $("#editSubURL").val());
    formData.append("server", $("#editSubServer").val());
    formData.append("extra_notes", $("#editSubNotes").val());

    var selectedTargets = $("#editSubChannels option:selected").toArray().map(item => item.value).join(';');
    formData.append("targets", selectedTargets);

    var imageFile = $("#editSubImage")[0].files[0];
    if (imageFile) {
        formData.append("image", imageFile);
    }

    if (uuid === "-1") {
        newSubscription(formData).then(resp => {
            loadSubscriptions();
            $("#subEditModal").modal("hide");
        })
        showToast("success", "Subscription Created", `${subName} successfully created.`);
    }
    else {
        editSubscription(uuid, formData).then(resp => {
            loadSubscriptions();
            $("#subEditModal").modal("hide");
            showToast("success", "Subscription Modified", `${subName} successfully modified.`);
        });
    }
}