/// <reference path="..\..\GSMyAdmin\WebRoot\Scripts\AMP.js" />
/// <reference path="..\..\GSMyAdmin\WebRoot\Scripts\UI.js" />
/// <reference path="..\..\GSMyAdmin\WebRoot\Scripts\API.js" />
/// <reference path="..\..\GSMyAdmin\WebRoot\Scripts\Common.js" />

/* jshint undef: true, unused: false */
/* global API,UI,PluginHandler */
/* eslint eqeqeq: "off", curly: "error", require-atomic-updates: "off" */

this.plugin = {
    AMPDataLoaded: async function () {
        const exts = currentSettings["GenericModule.Meta.ImportableExtensions"].value();
        for (const e of exts) {
            Features.FileManagerPlugin.RegisterContextMenuHandler(e.slice(1), "Import Configuration", importSettingsFile);
        }
        const importable = currentSettings["GenericModule.Meta.ImportableFilenames"].value();
        for (const f of importable) {
            Features.FileManagerPlugin.RegisterControlledFile(f, true, importSettingsFile, "Please import any changes so they are not overwritten by AMP.");
        }
        const exclusiveControl = currentSettings["GenericModule.Meta.ExclusiveControlFilenames"].value();
        for (const f of exclusiveControl) {
            Features.FileManagerPlugin.RegisterControlledFile(f, false, importSettingsFile, "This file is exclusively controlled by AMP and cannot be manually edited. Edit the settings in this file via the Configuration menu.");
        }
        await API.GenericModule.RequestServerInfoAsync();
    },
    PushedMessage: async function (source, message, parameters) {
        switch (message) {
            case "ServerInfoChanged":
                {
                    //Turn the parameters object into an array of KeyValuePairVM
                    const info = Object.keys(parameters).map(k => new KeyValuePairVM(k, parameters[k]));
                    viewModels.support.extraServerInfo.removeAll();
                    ko.utils.arrayPushAll(viewModels.support.extraServerInfo, info);
                    break;
                }
            case "ServerAuthURLPrompt":
                {
                    const url = parameters?.["Url"];
                    if (!url) return;

                    const parsedUrl = tryParseUrl(url);
                    if (!parsedUrl) {
                        UI.ShowModalAsync("Invalid URL", "The provided URL could not be parsed.", UI.Icons.Warning, UI.OKActionOnly, null, null);
                        return;
                    }

                    const domain = parsedUrl.hostname;
                    const protocol = parsedUrl.protocol.replace(":", "");

                    if (protocol !== "https") {
                        console.log("Refusing to show authentication URL prompt for non-HTTPS URL.");
                        return;
                    }

                    const promptResult = await UI.ShowModalAsync("Server login required", { text: "This server requires you to login to an external service to run this application.", subtitle: url }, UI.Icons.Question, [
                        new UI.ModalAction(`Continue to ${domain}`, 0, "bgGreen"),
                        new UI.ModalAction(`Copy URL to Clipboard`, 10),
                        new UI.ModalAction("Close", 30, "bgRed")
                    ]);

                    switch (promptResult) {
                        case 0:
                            window.open(url, "_blank");
                            break;
                        case 10:
                            if (!navigator.clipboard) {
                                UI.ShowModalAsync("Clipboard API not available", "Copying to clipboard requires that AMP is accessed from localhost or over https.", UI.Icons.Warning, UI.OKActionOnly, null, null);
                                return;
                            }
                            try {
                                await navigator.clipboard.writeText(url);
                            } catch {
                                UI.ShowModalAsync("Clipboard Error", "Failed to copy URL to clipboard.", UI.Icons.Warning, UI.OKActionOnly, null, null);
                            }
                            break;
                        case 30:
                            // Do nothing, user closed the prompt
                            break;
                    }

                    break;
                }
        }
    }
};

function tryParseUrl(url) {
    try { return new URL(url); } catch { /* noop */ }
    try { return new URL(url, window.location.origin); } catch { /* noop */ }
    return null;
}

async function importSettingsFile(file) {
    try {
        const settingUpdates = await API.GenericModule.ImportConfigAsync(file.directory + file.name);
        const available = Object.keys(settingUpdates).length;
        await API.Core.SetConfigs(settingUpdates);
        UI.ShowModalAsync("Import Complete", `${available} entries were successfully imported.`, UI.Icons.Info, UI.OKActionOnly, null, null);
    } catch (err) {
        UI.ShowModalAsync("Import Failed", `An error occurred during import: ${err?.message ?? err}`, UI.Icons.Warning, UI.OKActionOnly, null, null);
    }
}
