"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdaptiveApplet = void 0;
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
var Enums = require("./enums");
var Utils = require("./utils");
var shared_1 = require("./shared");
var activity_request_1 = require("./activity-request");
var strings_1 = require("./strings");
var card_elements_1 = require("./card-elements");
var serialization_1 = require("./serialization");
function logEvent(level, message) {
    var optionalParams = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        optionalParams[_i - 2] = arguments[_i];
    }
    if (shared_1.GlobalSettings.applets.logEnabled) {
        if (shared_1.GlobalSettings.applets.onLogEvent) {
            shared_1.GlobalSettings.applets.onLogEvent(level, message, optionalParams);
        }
        else {
            /* eslint-disable no-console */
            switch (level) {
                case Enums.LogLevel.Warning:
                    console.warn(message, optionalParams);
                    break;
                case Enums.LogLevel.Error:
                    console.error(message, optionalParams);
                    break;
                default:
                    console.log(message, optionalParams);
                    break;
            }
            /* eslint-enable no-console */
        }
    }
}
var ActivityRequest = /** @class */ (function () {
    function ActivityRequest(action, trigger, consecutiveActions) {
        this.action = action;
        this.trigger = trigger;
        this.consecutiveActions = consecutiveActions;
        this.attemptNumber = 0;
    }
    // eslint-disable-next-line @typescript-eslint/require-await
    ActivityRequest.prototype.retryAsync = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (this.onSend) {
                    this.onSend(this);
                }
                return [2 /*return*/];
            });
        });
    };
    return ActivityRequest;
}());
var AdaptiveApplet = /** @class */ (function () {
    function AdaptiveApplet() {
        this._allowAutomaticCardUpdate = false;
        this.renderedElement = document.createElement("div");
        this.renderedElement.className = "aaf-cardHost";
        this.renderedElement.style.position = "relative";
        this.renderedElement.style.display = "flex";
        this.renderedElement.style.flexDirection = "column";
        this._cardHostElement = document.createElement("div");
        this._refreshButtonHostElement = document.createElement("div");
        this._refreshButtonHostElement.className = "aaf-refreshButtonHost";
        this._refreshButtonHostElement.style.display = "none";
        this.renderedElement.appendChild(this._cardHostElement);
        this.renderedElement.appendChild(this._refreshButtonHostElement);
    }
    AdaptiveApplet.prototype.displayCard = function (card) {
        if (card.renderedElement) {
            Utils.clearElementChildren(this._cardHostElement);
            this._refreshButtonHostElement.style.display = "none";
            this._cardHostElement.appendChild(card.renderedElement);
        }
        else {
            throw new Error("displayCard: undefined card.");
        }
    };
    AdaptiveApplet.prototype.showManualRefreshButton = function (refreshAction) {
        var _this = this;
        var displayBuiltInManualRefreshButton = this.onShowManualRefreshButton
            ? this.onShowManualRefreshButton(this)
            : true;
        if (displayBuiltInManualRefreshButton) {
            this._refreshButtonHostElement.style.display = "none";
            var renderedRefreshButton = undefined;
            if (this.onRenderManualRefreshButton) {
                renderedRefreshButton = this.onRenderManualRefreshButton(this);
            }
            else {
                var message = strings_1.Strings.runtime.refreshThisCard();
                if (shared_1.GlobalSettings.applets.refresh.mode === Enums.RefreshMode.Automatic) {
                    var autoRefreshPausedMessage = strings_1.Strings.runtime.automaticRefreshPaused();
                    if (autoRefreshPausedMessage[autoRefreshPausedMessage.length - 1] !== " ") {
                        autoRefreshPausedMessage += " ";
                    }
                    message = strings_1.Strings.runtime.clckToRestartAutomaticRefresh();
                }
                var cardPayload = {
                    type: "AdaptiveCard",
                    version: "1.2",
                    body: [
                        {
                            type: "RichTextBlock",
                            horizontalAlignment: "right",
                            inlines: [
                                {
                                    type: "TextRun",
                                    text: message,
                                    selectAction: {
                                        type: "Action.Submit",
                                        id: "refreshCard"
                                    }
                                }
                            ]
                        }
                    ]
                };
                var card = new card_elements_1.AdaptiveCard();
                card.parse(cardPayload, new card_elements_1.SerializationContext(serialization_1.Versions.v1_2));
                card.onExecuteAction = function (action) {
                    if (action.id === "refreshCard") {
                        Utils.clearElementChildren(_this._refreshButtonHostElement);
                        _this.internalExecuteAction(refreshAction, activity_request_1.ActivityRequestTrigger.Automatic, 0);
                    }
                };
                renderedRefreshButton = card.render();
            }
            if (renderedRefreshButton) {
                Utils.clearElementChildren(this._refreshButtonHostElement);
                this._refreshButtonHostElement.appendChild(renderedRefreshButton);
                this._refreshButtonHostElement.style.removeProperty("display");
            }
        }
    };
    AdaptiveApplet.prototype.createActivityRequest = function (action, trigger, consecutiveActions) {
        var _this = this;
        if (this.card) {
            var request_1 = new ActivityRequest(action, trigger, consecutiveActions);
            request_1.onSend = function (sender) {
                sender.attemptNumber++;
                void _this.internalSendActivityRequestAsync(request_1);
            };
            var cancel = this.onPrepareActivityRequest
                ? !this.onPrepareActivityRequest(this, request_1, action)
                : false;
            return cancel ? undefined : request_1;
        }
        else {
            throw new Error("createActivityRequest: no card has been set.");
        }
    };
    AdaptiveApplet.prototype.createMagicCodeInputCard = function (attemptNumber) {
        var payload = {
            type: "AdaptiveCard",
            version: "1.0",
            body: [
                {
                    type: "TextBlock",
                    color: "attention",
                    text: attemptNumber === 1 ? undefined : "That didn't work... let's try again.",
                    wrap: true,
                    horizontalAlignment: "center"
                },
                {
                    type: "TextBlock",
                    text: 'Please login in the popup. You will obtain a magic code. Paste that code below and select "Submit"',
                    wrap: true,
                    horizontalAlignment: "center"
                },
                {
                    type: "Input.Text",
                    id: "magicCode",
                    placeholder: "Enter magic code"
                },
                {
                    type: "ActionSet",
                    horizontalAlignment: "center",
                    actions: [
                        {
                            type: "Action.Submit",
                            id: AdaptiveApplet._submitMagicCodeActionId,
                            title: "Submit"
                        },
                        {
                            type: "Action.Submit",
                            id: AdaptiveApplet._cancelMagicCodeAuthActionId,
                            title: "Cancel"
                        }
                    ]
                }
            ]
        };
        var card = new card_elements_1.AdaptiveCard();
        card.parse(payload);
        return card;
    };
    AdaptiveApplet.prototype.cancelAutomaticRefresh = function () {
        if (this._allowAutomaticCardUpdate) {
            logEvent(Enums.LogLevel.Warning, "Automatic card refresh has been cancelled as a result of the user interacting with the card.");
        }
        this._allowAutomaticCardUpdate = false;
    };
    AdaptiveApplet.prototype.createSerializationContext = function () {
        return this.onCreateSerializationContext
            ? this.onCreateSerializationContext(this)
            : new card_elements_1.SerializationContext();
    };
    AdaptiveApplet.prototype.internalSetCard = function (payload, consecutiveActions) {
        var _this = this;
        if (typeof payload === "object" && payload["type"] === "AdaptiveCard") {
            this._cardPayload = payload;
        }
        if (this._cardPayload) {
            try {
                var card = new card_elements_1.AdaptiveCard();
                if (this.hostConfig) {
                    card.hostConfig = this.hostConfig;
                }
                var serializationContext = this.createSerializationContext();
                card.parse(this._cardPayload, serializationContext);
                var doChangeCard = this.onCardChanging
                    ? this.onCardChanging(this, this._cardPayload)
                    : true;
                if (doChangeCard) {
                    this._card = card;
                    if (this._card.authentication &&
                        this._card.authentication.tokenExchangeResource &&
                        this.onPrefetchSSOToken) {
                        this.onPrefetchSSOToken(this, this._card.authentication.tokenExchangeResource);
                    }
                    this._card.onExecuteAction = function (action) {
                        // If the user takes an action, cancel any pending automatic refresh
                        _this.cancelAutomaticRefresh();
                        _this.internalExecuteAction(action, activity_request_1.ActivityRequestTrigger.Manual, 0);
                    };
                    this._card.onInputValueChanged = function (input) {
                        var _a, _b, _c;
                        // If the user modifies an input, cancel any pending automatic refresh
                        _this.cancelAutomaticRefresh();
                        if (input instanceof card_elements_1.ChoiceSetInput && input.isDynamicTypeahead()) {
                            var filter = input.getFilterForDynamicSearch();
                            if (filter) {
                                var dataQueryAction = new card_elements_1.DataQuery();
                                dataQueryAction.filter = filter;
                                dataQueryAction.dataset = ((_a = input.choicesData) === null || _a === void 0 ? void 0 : _a.dataset) || "";
                                dataQueryAction.count = (_b = input.choicesData) === null || _b === void 0 ? void 0 : _b.count;
                                dataQueryAction.skip = (_c = input.choicesData) === null || _c === void 0 ? void 0 : _c.skip;
                                _this._choiceSet = input;
                                _this.internalExecuteAction(dataQueryAction, activity_request_1.ActivityRequestTrigger.Manual, 0 // consecutiveActions
                                );
                            }
                        }
                    };
                    this._card.render();
                    if (this._card.renderedElement) {
                        this.displayCard(this._card);
                        if (this.onCardChanged) {
                            this.onCardChanged(this);
                        }
                        if (this._card.refresh) {
                            if (shared_1.GlobalSettings.applets.refresh.mode ===
                                Enums.RefreshMode.Automatic &&
                                consecutiveActions <
                                    shared_1.GlobalSettings.applets.refresh
                                        .maximumConsecutiveAutomaticRefreshes) {
                                if (shared_1.GlobalSettings.applets.refresh.timeBetweenAutomaticRefreshes <=
                                    0) {
                                    logEvent(Enums.LogLevel.Info, "Triggering automatic card refresh number " +
                                        (consecutiveActions + 1));
                                    this.internalExecuteAction(this._card.refresh.action, activity_request_1.ActivityRequestTrigger.Automatic, consecutiveActions + 1);
                                }
                                else {
                                    logEvent(Enums.LogLevel.Info, "Scheduling automatic card refresh number " +
                                        (consecutiveActions + 1) +
                                        " in " +
                                        shared_1.GlobalSettings.applets.refresh
                                            .timeBetweenAutomaticRefreshes +
                                        "ms");
                                    var action_1 = this._card.refresh.action;
                                    this._allowAutomaticCardUpdate = true;
                                    window.setTimeout(function () {
                                        if (_this._allowAutomaticCardUpdate) {
                                            _this.internalExecuteAction(action_1, activity_request_1.ActivityRequestTrigger.Automatic, consecutiveActions + 1);
                                        }
                                    }, shared_1.GlobalSettings.applets.refresh.timeBetweenAutomaticRefreshes);
                                }
                            }
                            else if (shared_1.GlobalSettings.applets.refresh.mode !== Enums.RefreshMode.Disabled) {
                                if (consecutiveActions > 0) {
                                    logEvent(Enums.LogLevel.Warning, "Stopping automatic refreshes after " +
                                        consecutiveActions +
                                        " consecutive refreshes.");
                                }
                                else {
                                    logEvent(Enums.LogLevel.Warning, "The card has a refresh section, but automatic refreshes are disabled.");
                                }
                                if (shared_1.GlobalSettings.applets.refresh
                                    .allowManualRefreshesAfterAutomaticRefreshes ||
                                    shared_1.GlobalSettings.applets.refresh.mode === Enums.RefreshMode.Manual) {
                                    logEvent(Enums.LogLevel.Info, "Showing manual refresh button.");
                                    this.showManualRefreshButton(this._card.refresh.action);
                                }
                            }
                        }
                    }
                }
            }
            catch (error) {
                // Ignore all errors
                logEvent(Enums.LogLevel.Error, "setCard: " + error);
            }
        }
    };
    AdaptiveApplet.prototype.internalExecuteAction = function (action, trigger, consecutiveActions) {
        if (action instanceof card_elements_1.UniversalAction) {
            if (this.channelAdapter) {
                var request = this.createActivityRequest(action, trigger, consecutiveActions);
                if (request) {
                    void request.retryAsync();
                }
            }
            else {
                throw new Error("internalExecuteAction: No channel adapter set.");
            }
        }
        if (this.onAction) {
            this.onAction(this, action);
        }
    };
    AdaptiveApplet.prototype.createProgressOverlay = function (request) {
        if (!this._progressOverlay) {
            if (this.onCreateProgressOverlay) {
                this._progressOverlay = this.onCreateProgressOverlay(this, request);
            }
            else {
                this._progressOverlay = document.createElement("div");
                this._progressOverlay.className = "aaf-progress-overlay";
                var spinner = document.createElement("div");
                spinner.className = "aaf-spinner";
                spinner.style.width = "28px";
                spinner.style.height = "28px";
                this._progressOverlay.appendChild(spinner);
            }
        }
        return this._progressOverlay;
    };
    AdaptiveApplet.prototype.removeProgressOverlay = function (request) {
        if (this.onRemoveProgressOverlay) {
            this.onRemoveProgressOverlay(this, request);
        }
        if (this._progressOverlay !== undefined) {
            this.renderedElement.removeChild(this._progressOverlay);
            this._progressOverlay = undefined;
        }
    };
    AdaptiveApplet.prototype.activityRequestSucceeded = function (response, parsedContent) {
        if (this.onActivityRequestSucceeded) {
            this.onActivityRequestSucceeded(this, response, parsedContent);
        }
    };
    AdaptiveApplet.prototype.activityRequestFailed = function (response) {
        return this.onActivityRequestFailed
            ? this.onActivityRequestFailed(this, response)
            : shared_1.GlobalSettings.applets.defaultTimeBetweenRetryAttempts;
    };
    AdaptiveApplet.prototype.showAuthCodeInputDialog = function (request) {
        var _this = this;
        var showBuiltInAuthCodeInputCard = this.onShowAuthCodeInputDialog
            ? this.onShowAuthCodeInputDialog(this, request)
            : true;
        if (showBuiltInAuthCodeInputCard) {
            var authCodeInputCard = this.createMagicCodeInputCard(request.attemptNumber);
            authCodeInputCard.render();
            authCodeInputCard.onExecuteAction = function (submitMagicCodeAction) {
                if (_this.card && submitMagicCodeAction instanceof card_elements_1.SubmitAction) {
                    switch (submitMagicCodeAction.id) {
                        case AdaptiveApplet._submitMagicCodeActionId:
                            var authCode = undefined;
                            if (submitMagicCodeAction.data &&
                                typeof submitMagicCodeAction.data["magicCode"] === "string") {
                                authCode = submitMagicCodeAction.data["magicCode"];
                            }
                            if (authCode) {
                                _this.displayCard(_this.card);
                                request.authCode = authCode;
                                void request.retryAsync();
                            }
                            else {
                                alert("Please enter the magic code you received.");
                            }
                            break;
                        case AdaptiveApplet._cancelMagicCodeAuthActionId:
                            logEvent(Enums.LogLevel.Warning, "Authentication cancelled by user.");
                            _this.displayCard(_this.card);
                            break;
                        default:
                            logEvent(Enums.LogLevel.Error, "Unexpected action taken from magic code input card (id = " +
                                submitMagicCodeAction.id +
                                ")");
                            alert(strings_1.Strings.magicCodeInputCard.somethingWentWrong());
                            break;
                    }
                }
            };
            this.displayCard(authCodeInputCard);
        }
    };
    AdaptiveApplet.prototype.internalSendActivityRequestAsync = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var action;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.channelAdapter) {
                            throw new Error("internalSendActivityRequestAsync: channelAdapter is not set.");
                        }
                        action = request.action;
                        if (!(action instanceof card_elements_1.ExecuteAction)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.internalSendExecuteRequestAsync(request)];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 2:
                        if (!(action instanceof card_elements_1.DataQuery)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.internalSendDataQueryRequestAsync(request)];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 4: throw new Error("internalSendActivityRequestAsync: Unhandled Action Type");
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    AdaptiveApplet.prototype.internalSendExecuteRequestAsync = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var overlay, done, _loop_1, this_1, state_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.channelAdapter) {
                            throw new Error("internalSendExecuteRequestAsync: channelAdapter is not set.");
                        }
                        overlay = this.createProgressOverlay(request);
                        if (overlay !== undefined) {
                            this.renderedElement.appendChild(overlay);
                        }
                        done = false;
                        _loop_1 = function () {
                            var response, error_1, parsedContent, retryIn_1, attemptOAuth, left, top_1;
                            return __generator(this, function (_b) {
                                switch (_b.label) {
                                    case 0:
                                        response = undefined;
                                        if (request.attemptNumber === 1) {
                                            logEvent(Enums.LogLevel.Info, "Sending activity request to channel (attempt " + request.attemptNumber + ")");
                                        }
                                        else {
                                            logEvent(Enums.LogLevel.Info, "Re-sending activity request to channel (attempt " + request.attemptNumber + ")");
                                        }
                                        _b.label = 1;
                                    case 1:
                                        _b.trys.push([1, 3, , 4]);
                                        return [4 /*yield*/, this_1.channelAdapter.sendRequestAsync(request)];
                                    case 2:
                                        response = _b.sent();
                                        return [3 /*break*/, 4];
                                    case 3:
                                        error_1 = _b.sent();
                                        logEvent(Enums.LogLevel.Error, "Activity request failed: " + error_1);
                                        this_1.removeProgressOverlay(request);
                                        done = true;
                                        return [3 /*break*/, 4];
                                    case 4:
                                        if (!response) return [3 /*break*/, 10];
                                        if (!(response instanceof activity_request_1.SuccessResponse)) return [3 /*break*/, 5];
                                        this_1.removeProgressOverlay(request);
                                        if (response.rawContent === undefined) {
                                            throw new Error("internalSendExecuteRequestAsync: Action.Execute result is undefined");
                                        }
                                        parsedContent = response.rawContent;
                                        try {
                                            parsedContent = JSON.parse(response.rawContent);
                                        }
                                        catch (_c) {
                                            // Leave parseContent as is
                                        }
                                        if (typeof parsedContent === "string") {
                                            logEvent(Enums.LogLevel.Info, "The activity request returned a string after " +
                                                request.attemptNumber +
                                                " attempt(s).");
                                            this_1.activityRequestSucceeded(response, parsedContent);
                                        }
                                        else if (typeof parsedContent === "object" &&
                                            parsedContent["type"] === "AdaptiveCard") {
                                            logEvent(Enums.LogLevel.Info, "The activity request returned an Adaptive Card after " +
                                                request.attemptNumber +
                                                " attempt(s).");
                                            this_1.internalSetCard(parsedContent, request.consecutiveActions);
                                            this_1.activityRequestSucceeded(response, this_1.card);
                                        }
                                        else {
                                            throw new Error("internalSendExecuteRequestAsync: Action.Execute result is of unsupported type (" +
                                                typeof response.rawContent +
                                                ")");
                                        }
                                        done = true;
                                        return [3 /*break*/, 10];
                                    case 5:
                                        if (!(response instanceof activity_request_1.ErrorResponse)) return [3 /*break*/, 9];
                                        retryIn_1 = this_1.activityRequestFailed(response);
                                        if (!(retryIn_1 >= 0 &&
                                            request.attemptNumber < shared_1.GlobalSettings.applets.maximumRetryAttempts)) return [3 /*break*/, 7];
                                        logEvent(Enums.LogLevel.Warning, "Activity request failed: ".concat(response.error.message, ". Retrying in ").concat(retryIn_1, "ms"));
                                        request.attemptNumber++;
                                        return [4 /*yield*/, new Promise(function (resolve, _reject) {
                                                window.setTimeout(function () {
                                                    resolve();
                                                }, retryIn_1);
                                            })];
                                    case 6:
                                        _b.sent();
                                        return [3 /*break*/, 8];
                                    case 7:
                                        logEvent(Enums.LogLevel.Error, "Activity request failed: ".concat(response.error.message, ". Giving up after ").concat(request.attemptNumber, " attempt(s)"));
                                        this_1.removeProgressOverlay(request);
                                        done = true;
                                        _b.label = 8;
                                    case 8: return [3 /*break*/, 10];
                                    case 9:
                                        if (response instanceof activity_request_1.LoginRequestResponse) {
                                            logEvent(Enums.LogLevel.Info, "The activity request returned a LoginRequestResponse after " +
                                                request.attemptNumber +
                                                " attempt(s).");
                                            if (request.attemptNumber <= shared_1.GlobalSettings.applets.maximumRetryAttempts) {
                                                attemptOAuth = true;
                                                if (response.tokenExchangeResource && this_1.onSSOTokenNeeded) {
                                                    // Attempt to use SSO. The host will return true if it can handle SSO, in which case
                                                    // we bypass OAuth
                                                    attemptOAuth = !this_1.onSSOTokenNeeded(this_1, request, response.tokenExchangeResource);
                                                }
                                                if (attemptOAuth) {
                                                    // Attempt to use OAuth
                                                    this_1.removeProgressOverlay(request);
                                                    if (response.signinButton === undefined) {
                                                        throw new Error("internalSendExecuteRequestAsync: the login request doesn't contain a valid signin URL.");
                                                    }
                                                    logEvent(Enums.LogLevel.Info, "Login required at " + response.signinButton.value);
                                                    if (this_1.onShowSigninPrompt) {
                                                        // Bypass the built-in auth prompt if the host app handles it
                                                        this_1.onShowSigninPrompt(this_1, request, response.signinButton);
                                                    }
                                                    else {
                                                        this_1.showAuthCodeInputDialog(request);
                                                        left = window.screenX +
                                                            (window.outerWidth - shared_1.GlobalSettings.applets.authPromptWidth) /
                                                                2;
                                                        top_1 = window.screenY +
                                                            (window.outerHeight - shared_1.GlobalSettings.applets.authPromptHeight) /
                                                                2;
                                                        window.open(response.signinButton.value, response.signinButton.title
                                                            ? response.signinButton.title
                                                            : "Sign in", "width=".concat(shared_1.GlobalSettings.applets.authPromptWidth, ",height=").concat(shared_1.GlobalSettings.applets.authPromptHeight, ",left=").concat(left, ",top=").concat(top_1));
                                                    }
                                                }
                                            }
                                            else {
                                                logEvent(Enums.LogLevel.Error, "Authentication failed. Giving up after " +
                                                    request.attemptNumber +
                                                    " attempt(s)");
                                                alert(strings_1.Strings.magicCodeInputCard.authenticationFailed());
                                            }
                                            return [2 /*return*/, "break"];
                                        }
                                        else {
                                            throw new Error("Unhandled response type: " + JSON.stringify(response));
                                        }
                                        _b.label = 10;
                                    case 10: return [2 /*return*/];
                                }
                            });
                        };
                        this_1 = this;
                        _a.label = 1;
                    case 1:
                        if (!!done) return [3 /*break*/, 3];
                        return [5 /*yield**/, _loop_1()];
                    case 2:
                        state_1 = _a.sent();
                        if (state_1 === "break")
                            return [3 /*break*/, 3];
                        return [3 /*break*/, 1];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    AdaptiveApplet.prototype.internalSendDataQueryRequestAsync = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var filter, response, error_2, rawResponse, parsedResponse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.channelAdapter) {
                            throw new Error("internalSendDataQueryRequestAsync: channel adapter not set");
                        }
                        filter = request.action.filter;
                        if (!this._choiceSet) return [3 /*break*/, 5];
                        this._choiceSet.showLoadingIndicator();
                        response = undefined;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.channelAdapter.sendRequestAsync(request)];
                    case 2:
                        response = _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        error_2 = _a.sent();
                        this._choiceSet.showErrorIndicator(filter, "Unable to load");
                        logEvent(Enums.LogLevel.Error, "Activity request failed: " + error_2);
                        return [3 /*break*/, 4];
                    case 4:
                        if (response) {
                            if (response instanceof activity_request_1.SuccessResponse) {
                                rawResponse = response.rawContent;
                                if (rawResponse) {
                                    parsedResponse = void 0;
                                    try {
                                        parsedResponse = JSON.parse(rawResponse);
                                    }
                                    catch (error) {
                                        this._choiceSet.showErrorIndicator(filter, "Unable to load");
                                        throw new Error("internalSendDataQueryRequestAsync: Cannot parse response object: " +
                                            rawResponse);
                                    }
                                    if (typeof parsedResponse === "object") {
                                        this._choiceSet.renderChoices(filter, parsedResponse);
                                        this.activityRequestSucceeded(response, rawResponse);
                                    }
                                    else {
                                        this._choiceSet.showErrorIndicator(filter, "Error loading results");
                                        throw new Error("internalSendDataQueryRequestAsync: Data.Query result is of unsupported type (" +
                                            typeof rawResponse +
                                            ")");
                                    }
                                }
                                else {
                                    this._choiceSet.showErrorIndicator(filter, "Unable to load");
                                    throw new Error("internalSendDataQueryRequestAsync: Data.Query result is undefined");
                                }
                            }
                            else if (response instanceof activity_request_1.ErrorResponse) {
                                this._choiceSet.showErrorIndicator(filter, response.error.message || "Error loading results");
                                logEvent(Enums.LogLevel.Error, "Activity request failed: ".concat(response.error.message, "."));
                                this.activityRequestFailed(response);
                            }
                            else {
                                this._choiceSet.showErrorIndicator(filter, "Unable to load");
                                throw new Error("Unhandled response type: " + JSON.stringify(response));
                            }
                        }
                        else {
                            this._choiceSet.removeLoadingIndicator();
                        }
                        _a.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    AdaptiveApplet.prototype.refreshCard = function () {
        if (this._card && this._card.refresh) {
            this.internalExecuteAction(this._card.refresh.action, activity_request_1.ActivityRequestTrigger.Manual, 0);
        }
    };
    AdaptiveApplet.prototype.setCard = function (payload) {
        this.internalSetCard(payload, 0);
    };
    Object.defineProperty(AdaptiveApplet.prototype, "card", {
        get: function () {
            return this._card;
        },
        enumerable: false,
        configurable: true
    });
    AdaptiveApplet._submitMagicCodeActionId = "submitMagicCode";
    AdaptiveApplet._cancelMagicCodeAuthActionId = "cancelMagicCodeAuth";
    return AdaptiveApplet;
}());
exports.AdaptiveApplet = AdaptiveApplet;
//# sourceMappingURL=adaptive-applet.js.map