// Zapier API key management dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

// Dialog dimensions. HeightSmall is used when the new-key panel is hidden;
// HeightLarge expands to reveal it after a successful key generation.
var nZapierDlgWidth       = 460;
var nZapierDlgHeightSmall = 360;
var nZapierDlgHeightLarge = 540;


// ZapierDlgResize
// Resizes the open igDialog to nHeight pixels, capped at 95% of the viewport
// so the dialog never extends below the bottom of the screen on small displays.
function ZapierDlgResize(nHeight) {
    var nWindowHeight = $(window).height();
    if (nHeight > nWindowHeight * 0.95) nHeight = Math.floor(nWindowHeight * 0.95);
    $("#igDialogZapierApiKey").igDialog("option", "height", nHeight);
}


// OnManageZapierApiKey
// Opens the Zapier API Key dialog. Called from the View ribbon "Zapier API Key" button.
// The dialog opens small (new-key panel hidden) and loads the user's current key status.
function OnManageZapierApiKey() {

    // Cap width and height to 95% of the viewport on small screens.
    var nDlgWidth = nZapierDlgWidth;
    var nDlgHeight = nZapierDlgHeightSmall;
    var nWindowWidth  = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth  < nDlgWidth)  nDlgWidth  = Math.floor(nWindowWidth  * 0.95);
    if (nWindowHeight < nDlgHeight) nDlgHeight = Math.floor(nWindowHeight * 0.95);

    // Initialize and open the igDialog. igDialog must be re-initialized each open
    // because closing it destroys the widget state.
    $("#igDialogZapierApiKey").igDialog({ modal: true, headerText: "Zapier API Key", width: nDlgWidth, height: nDlgHeight, resizable: false, closeOnEscape: true, openAnimation: "", closeAnimation: "fade" });
    $("#igDialogZapierApiKey").igDialog("open");

    // Hide the new-key panel and trace level row until status loads.
    $("#ZapierApiKeyNewKeyPanel").hide();
    $("#ZapierTraceLevelRow").hide();
    $("#ZapierApiKeyPrefixLabel").text("Loading...");

    // Wire button handlers. unbind() first prevents duplicate handlers if the dialog
    // is opened more than once per page session.
    $("#ZapierApiKeyGenerateButton").unbind().click(function () { OnZapierGenerateKey(); });
    $("#ZapierApiKeyRevokeButton").unbind().click(function () { OnZapierRevokeKey(); });
    $("#ZapierApiKeyCopyButton").unbind().click(function () { OnZapierCopyKey(); });
    $("#ZapierApiKeyCloseButton").unbind().click(function () { CloseZapierApiKeyDialog(); });
    $("#ZapierTraceLevelSelect").unbind().change(function () { OnZapierTraceLevelChange(); });

    // Load the current key prefix and trace level from the server.
    AjaxGetZapierApiKeyStatus();
}


// CloseZapierApiKeyDialog
// Closes the Zapier API Key dialog.
function CloseZapierApiKeyDialog() {
    $("#igDialogZapierApiKey").igDialog("close");
}


// OnZapierGenerateKey
// Generates a new API key for the logged-in user. Any previously active key is revoked
// server-side before the new one is created. The plaintext key is returned once and
// displayed in the new-key panel; it is never stored and cannot be retrieved later.
// TraceLevel is reset to 0 on the new key; the user can adjust it via the dropdown.
function OnZapierGenerateKey() {

    // Disable the button while the request is in flight to prevent double-submission.
    $("#ZapierApiKeyGenerateButton").prop("disabled", true).val("Generating...");

    console.log("Zapier: GenerateKey request");
    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGenerateZapierApiKey",
        type: "POST",
        contentType: "application/json",
        success: function (response) {
            console.log("Zapier: GenerateKey response", response);
            // Re-enable the button regardless of success or failure.
            $("#ZapierApiKeyGenerateButton").prop("disabled", false).val("Generate New Key");
            if (response.Success) {
                // Show the key prefix in the status line so the user can identify it later.
                $("#ZapierApiKeyPrefixLabel").text(response.KeyPrefix + "...  (active)");
                // Populate and reveal the new-key panel, then expand the dialog to fit.
                $("#ZapierApiKeyPlaintextBox").val(response.PlaintextKey);
                $("#ZapierApiKeyNewKeyPanel").show();
                // New key always starts at TraceLevel 0.
                $("#ZapierTraceLevelSelect").val("0");
                $("#ZapierTraceLevelRow").show();
                ZapierDlgResize(nZapierDlgHeightLarge);
                // Select the key text so the user can immediately Ctrl+C.
                $("#ZapierApiKeyPlaintextBox").select();
            } else {
                ToastError("Zapier API Key", response.ErrorResults);
            }
        },
        error: function (xhr) {
            console.log("Zapier: GenerateKey error", xhr.status, xhr.statusText);
            $("#ZapierApiKeyGenerateButton").prop("disabled", false).val("Generate New Key");
            ToastError("Zapier API Key", "Error " + xhr.status + ": " + xhr.statusText);
        }
    });
}


// OnZapierRevokeKey
// Prompts the user for confirmation before revoking. Uses the app's standard
// PopupYesNoWithCallback so the confirm dialog matches the app's visual style.
function OnZapierRevokeKey() {
    PopupYesNoWithCallback("Revoke Zapier API Key", "Revoke your Zapier API key? Any Zaps using it will stop working.", OnZapierRevokeKeyConfirmed, null);
}


// OnZapierRevokeKeyConfirmed
// Executes the revoke after the user clicks Yes in the confirm dialog.
// Marks all active keys for the user as inactive in the database.
function OnZapierRevokeKeyConfirmed() {
    console.log("Zapier: RevokeKey request");
    $.ajax({
        url: VirtualDirectory + "/Home/AjaxRevokeZapierApiKey",
        type: "POST",
        contentType: "application/json",
        success: function (response) {
            console.log("Zapier: RevokeKey response", response);
            if (response.Success) {
                // Update the status line, hide trace level row and new-key panel, shrink dialog.
                $("#ZapierApiKeyPrefixLabel").text("No active key");
                $("#ZapierApiKeyNewKeyPanel").hide();
                $("#ZapierTraceLevelRow").hide();
                ZapierDlgResize(nZapierDlgHeightSmall);
                ToastMessage("Zapier API key revoked.");
            } else {
                ToastError("Zapier API Key", response.ErrorResults);
            }
        },
        error: function (xhr) {
            console.log("Zapier: RevokeKey error", xhr.status, xhr.statusText);
            ToastError("Zapier API Key", "Error " + xhr.status + ": " + xhr.statusText);
        }
    });
}


// OnZapierCopyKey
// Copies the plaintext API key to the clipboard using the Clipboard API.
function OnZapierCopyKey() {
    var sKey = $("#ZapierApiKeyPlaintextBox").val();
    if (!sKey) return;
    navigator.clipboard.writeText(sKey).then(function () {
        ToastMessage("API key copied to clipboard.");
    }, function () {
        ToastError("Zapier API Key", "Could not copy to clipboard. Please select and copy the key manually.");
    });
}


// OnZapierTraceLevelChange
// Called when the user changes the trace level dropdown. Saves the new value immediately.
function OnZapierTraceLevelChange() {
    var nTraceLevel = parseInt($("#ZapierTraceLevelSelect").val(), 10);
    console.log("Zapier: SetTraceLevel request", nTraceLevel);
    $.ajax({
        url: VirtualDirectory + "/Home/AjaxSetZapierTraceLevel",
        type: "POST",
        data: { nTraceLevel: nTraceLevel },
        success: function (response) {
            console.log("Zapier: SetTraceLevel response", response);
            if (!response.Success) {
                ToastError("Zapier API Key", response.ErrorResults);
            }
        },
        error: function (xhr) {
            console.log("Zapier: SetTraceLevel error", xhr.status, xhr.statusText);
            ToastError("Zapier API Key", "Error " + xhr.status + ": " + xhr.statusText);
        }
    });
}


// AjaxGetZapierApiKeyStatus
// Loads the current API key status and trace level for the logged-in user.
// Called on dialog open. Shows only the key prefix (e.g. "st_abc123"), never the full key.
function AjaxGetZapierApiKeyStatus() {
    console.log("Zapier: GetApiKeyStatus request");
    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetZapierApiKeyStatus",
        type: "GET",
        success: function (response) {
            console.log("Zapier: GetApiKeyStatus response", response);
            if (response.Success) {
                // HasKey is false when no active key exists for this user.
                if (response.HasKey) {
                    $("#ZapierApiKeyPrefixLabel").text(response.KeyPrefix + "...  (active)");
                    $("#ZapierTraceLevelSelect").val(String(response.TraceLevel));
                    $("#ZapierTraceLevelRow").show();
                } else {
                    $("#ZapierApiKeyPrefixLabel").text("No active key");
                    $("#ZapierTraceLevelRow").hide();
                }
            } else {
                $("#ZapierApiKeyPrefixLabel").text("(error loading status)");
            }
        },
        error: function (xhr) {
            console.log("Zapier: GetApiKeyStatus error", xhr.status, xhr.statusText);
            $("#ZapierApiKeyPrefixLabel").text("(error loading status)");
        }
    });
}
