
$("#serverSettingsBtn").on("click", async function() {
    await showServerSettingsModal();
});

async function showServerSettingsModal() {
    const server = getCurrentlyActiveServer();
    var guildSettings;

    try { guildSettings = (await getGuildSettings(server.guild_id)).results[0] }
    catch (error) {
        console.error(error)
        return;
    }

    $("#guildSettingsId").val(guildSettings.id);
    $("#guildSettingsGuildId").val(guildSettings.guild_id);
    $("#guildSettingsActive").prop("checked", guildSettings.active);
    updateColourInput("guildSettingsDefaultEmbedColour", guildSettings.default_embed_colour);

    $("#serverSettingsModal").modal("show");
}

$("#serverSettingsForm").on("submit", async function(e) {
    e.preventDefault();

    var id = $("#guildSettingsId").val();
        guildId = $("#guildSettingsGuildId").val();
        active = $("#guildSettingsActive").prop("checked");
        defaultEmbedColour = getColourInputVal("guildSettingsDefaultEmbedColour", false);

    const pk = await saveGuildSettings(id, guildId, defaultEmbedColour, active);

    if (pk) {
        showToast("success", "Server Settings Saved", "Primary Key: " + pk);
    }

    updateDefaultSubEmbedColour();
    $("#serverSettingsModal").modal("hide");

})

async function saveGuildSettings(id, guildId, defaultEmbedColour, active) {
    var formData = new FormData();
    formData.append("guild_id", guildId);
    formData.append("default_embed_colour", defaultEmbedColour);
    formData.append("active", active);

    var response;
    try {
        response = await editGuildSettings(id, formData);
    }
    catch (err) {
        console.error(err);
        return false;
    }

    return response.id;
}
