const wrapper = document.getElementById("pluginsWrapper");
const uploadButton = document.getElementById("uploadButton");

async function loadPlugins() {
    const res = await fetch("/getPlugins");
    const plugins = await res.json();

    wrapper.innerHTML = "";

    plugins.forEach(plugin => {
        const div = document.createElement("div");
        div.className = "mod"; // gleiche CSS wie Mods 😏

        div.innerHTML = `
            <p>${plugin.name} <br> (${plugin.size} MB)</p>
            <button class="delete" onclick="deletePlugin('${plugin.name}')">Löschen</button>
        `;

        wrapper.appendChild(div);
    });
}

async function deletePlugin(name) {
    if (!confirm(`Plugin "${name}" löschen?`)) return;

    const res = await fetch("/deletePlugin", {
        method: "POST",
        headers: {"Content-Type":"application/json"},
        body: JSON.stringify({ name })
    });

    alert(await res.text());
    loadPlugins();
}

// Upload
uploadButton.onclick = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.multiple = true;
    input.accept = ".jar";

    input.onchange = async () => {
        const formData = new FormData();
        for (const file of input.files) {
            formData.append("plugins", file);
        }

        const res = await fetch("/uploadPlugins", {
            method: "POST",
            body: formData
        });

        alert(await res.text());
        loadPlugins();
    };

    input.click();
};

loadPlugins();