"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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.licenseManager = exports.getLicenseInfo = exports.applyLicense = exports.getLicenseCookie = exports.setUseLicenseWizard = exports.setRuntimeLicenseKey = exports.setLicenseCallback = exports.getLicenseLog = exports.debug = exports.logInfo = exports.setIsDebugLicensing = exports.setDependencies = void 0;
var app_1 = require("../../constants/app");
var BuildStamp_1 = require("../../Core/BuildStamp");
var Dictionary_1 = require("../../Core/Dictionary");
var Globals_1 = require("../../Core/Globals");
var localStorageApi_1 = require("../../Core/storage/localStorageApi");
var Telemetry_1 = require("../../Core/Telemetry");
var Color_1 = require("../../types/Color");
var licensingClasses_1 = require("../../types/licensingClasses");
var SurfaceType_1 = require("../../types/SurfaceType");
var cookie_1 = require("../../utils/cookie");
var licenseManager2dState_1 = require("./licenseManager2dState");
var licenseWizardPort = 24278;
var licenseWizardAlternatePort = 24279;
var portOverride = localStorageApi_1.localStorageApi.getLicenseWizardPort();
if (portOverride) {
    licenseWizardPort = portOverride;
    licenseWizardAlternatePort = licenseWizardPort + 1;
}
var fetchFromWizard = function (path) { return __awaiter(void 0, void 0, void 0, function () {
    var wizardUrl, response, err_1, maxport, wizardUrl, response, err_2;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 2, , 9]);
                wizardUrl = "http://localhost:" + licenseWizardPort.toString() + path;
                return [4 /*yield*/, fetch(wizardUrl)];
            case 1:
                response = _a.sent();
                return [2 /*return*/, response];
            case 2:
                err_1 = _a.sent();
                (0, exports.debug)("Could not connect to license wizard on port " + licenseWizardPort.toString());
                if (!(typeof localStorage !== "undefined")) return [3 /*break*/, 8];
                maxport = localStorageApi_1.localStorageApi.getLicenseWizardMaxPort();
                if (!maxport) return [3 /*break*/, 8];
                _a.label = 3;
            case 3:
                if (!(licenseWizardAlternatePort <= maxport)) return [3 /*break*/, 8];
                _a.label = 4;
            case 4:
                _a.trys.push([4, 6, , 7]);
                wizardUrl = "http://localhost:" + licenseWizardAlternatePort.toString() + path;
                return [4 /*yield*/, fetch(wizardUrl)];
            case 5:
                response = _a.sent();
                licenseWizardPort = licenseWizardAlternatePort;
                return [2 /*return*/, response];
            case 6:
                err_2 = _a.sent();
                (0, exports.debug)("Could not connect to license wizard on port " + licenseWizardAlternatePort.toString());
                licenseWizardAlternatePort = licenseWizardAlternatePort + 1;
                return [3 /*break*/, 7];
            case 7: return [3 /*break*/, 3];
            case 8: throw err_1;
            case 9: return [2 /*return*/];
        }
    });
}); };
var licenseDependencies = {
    fetchFromWizard: function (url) { return fetchFromWizard(url); },
    setCookie: function (name, val, validDays) { return (0, cookie_1.setCookie)(name, val, validDays); },
    getCookie: function (name) { return (0, cookie_1.getCookie)(name); },
    fetchForChallenge: function (url) { return fetch(url); },
    getInitialToken: function () {
        var _a;
        if (typeof document === "undefined")
            return null;
        var meta = document.querySelector('meta[name="x-scichart-license"]');
        return (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : null;
    },
    generateSimpleToken: function (orderId) { return null; }
};
var setDependencies = function (dependencies) { return (licenseDependencies = dependencies); };
exports.setDependencies = setDependencies;
var isDebug = null;
var setIsDebugLicensing = function (value, persist) {
    if (persist === void 0) { persist = false; }
    isDebug = value;
    if (persist || !value) {
        localStorageApi_1.localStorageApi.setIsLicenseDebug(value);
    }
};
exports.setIsDebugLicensing = setIsDebugLicensing;
var infoLog = [];
var debugLog = [];
var MAX_INFO_LOG_ENTRIES = 50;
var MAX_DEBUG_LOG_ENTRIES = 200;
var LS_LICENSE_LOG_KEY = 'scichartLicenseLog';
var logLevel = 'debug';
var outputMode = 'none';
var defaultEmitLog = function (entry) {
    var _a;
    if (outputMode === 'console' || isDebug) {
        console.log(entry.message);
    }
    if (outputMode === 'localStorage' && typeof localStorage !== 'undefined') {
        var t = new Date(entry.timestamp).toISOString().substring(11, 23);
        var line = "[".concat(entry.level === 'info' ? 'INFO ' : 'DEBUG', "] ").concat(t, " ").concat(entry.message, "\n");
        try {
            localStorage.setItem(LS_LICENSE_LOG_KEY, ((_a = localStorage.getItem(LS_LICENSE_LOG_KEY)) !== null && _a !== void 0 ? _a : '') + line);
        }
        catch (_) { /* storage full */ }
    }
};
var emitLogFn = defaultEmitLog;
/** @internal exported for testing */
var logInfo = function (message) {
    if (infoLog.length >= MAX_INFO_LOG_ENTRIES)
        infoLog.shift();
    var entry = { timestamp: Date.now(), level: 'info', message: message };
    infoLog.push(entry);
    if (logLevel === 'info' || logLevel === 'debug') {
        emitLogFn(entry);
    }
};
exports.logInfo = logInfo;
/** @internal exported for testing */
var debug = function (message) {
    if (isDebug === null) {
        isDebug = localStorageApi_1.localStorageApi.getIsLicenseDebug();
    }
    if (app_1.IS_TEST_ENV || isDebug) {
        var entry = { timestamp: Date.now(), level: 'debug', message: message };
        if (debugLog.length >= MAX_DEBUG_LOG_ENTRIES)
            debugLog.shift();
        debugLog.push(entry);
        if (logLevel === 'debug') {
            emitLogFn(entry);
        }
    }
};
exports.debug = debug;
var getLicenseLog = function () {
    return __spreadArray(__spreadArray([], infoLog, true), debugLog, true).sort(function (a, b) { return a.timestamp - b.timestamp; });
};
exports.getLicenseLog = getLicenseLog;
var formatLicenseLog = function () {
    return (0, exports.getLicenseLog)()
        .map(function (e) {
        var t = new Date(e.timestamp).toISOString().substring(11, 23);
        return "[".concat(e.level === 'info' ? 'INFO ' : 'DEBUG', "] ").concat(t, " ").concat(e.message);
    })
        .join('\n');
};
var clearLogs = function () {
    infoLog.length = 0;
    debugLog.length = 0;
};
(0, exports.logInfo)("SciChart version " + BuildStamp_1.libraryVersion);
// tslint:disable: no-console
var licenseCallback;
var setLicenseCallback = function (callback) {
    licenseCallback = callback;
};
exports.setLicenseCallback = setLicenseCallback;
// Cheap non-cryptographic hash for debug diagnostics — lets a customer compare
// the fingerprint of the key they pasted against a known-good fingerprint
// without having to share the full key. FNV-1a 32-bit; 8 hex chars.
var hashLicenseKey = function (key) {
    var h = 0x811c9dc5;
    for (var i = 0; i < key.length; i++) {
        h ^= key.charCodeAt(i);
        h = Math.imul(h, 0x01000193);
    }
    return (h >>> 0).toString(16).padStart(8, "0");
};
// Validation-state helpers — pick developer-licence vs runtime-key statuses based
// on whether we're talking to the local licensing wizard or a remote server.
var validatingStatus = function () {
    return licenseManager2dState_1.licenseManager2dState.isDev
        ? licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense
        : licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
};
var failedValidateStatus = function () {
    return licenseManager2dState_1.licenseManager2dState.isDev
        ? licensingClasses_1.LicenseCheckStatus.FailedToValidateDeveloperLicense
        : licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
};
var isValidating = function (s) {
    return s === licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense ||
        s === licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
};
var runtimeLicenseKey = "";
var getRuntimeLicenseKey = function () { return runtimeLicenseKey; };
var setRuntimeLicenseKey = function (value) {
    var prev = runtimeLicenseKey;
    runtimeLicenseKey = value;
    if (runtimeLicenseKey !== prev && runtimeLicenseKey !== "") {
        getAllLicenseContexts().forEach(function (lc) { return (0, exports.applyLicense)(lc, "setRuntimeLicenseKey"); });
    }
};
exports.setRuntimeLicenseKey = setRuntimeLicenseKey;
var useLicenseWizard = true;
var setUseLicenseWizard = function (value) {
    useLicenseWizard = value;
};
exports.setUseLicenseWizard = setUseLicenseWizard;
var retryTime = app_1.IS_TEST_ENV ? 0.1 : 5;
var maxretries = app_1.IS_TEST_ENV ? 12 : 10;
var serverLicenseEndpoint = "api/license";
var getServerLicenseEndpoint = function () { return serverLicenseEndpoint; };
var setServerLicenseEndpoint = function (value) {
    serverLicenseEndpoint = value;
};
var getLicenseFailCounts = 0;
var wizardTimer;
var licenseChallengeTimeout;
var getlicenseFromWizard = function (licenseContext) { return __awaiter(void 0, void 0, void 0, function () {
    var response, keyCode, _a, requiresValidation, trialExpired, err_3, licenseInfo;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _b.trys.push([0, 5, , 6]);
                if (checkStatus !== licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard &&
                    checkStatus !== licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard &&
                    checkStatus !== licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard)
                    return [2 /*return*/];
                (0, exports.debug)("Trying to get license from local license wizard");
                response = void 0;
                return [4 /*yield*/, licenseDependencies.fetchFromWizard("/license")];
            case 1:
                response = _b.sent();
                if (!response.ok) return [3 /*break*/, 3];
                return [4 /*yield*/, response.text()];
            case 2:
                keyCode = _b.sent();
                _a = setNewLicense(keyCode, licenseContext), requiresValidation = _a.requiresValidation, trialExpired = _a.trialExpired;
                if (requiresValidation) {
                    (0, exports.logInfo)("Got a developer license from local license wizard.  Validating...");
                    checkStatus = licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense;
                    dolicenseChallenge(licenseContext);
                }
                else if (trialExpired) {
                    checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard;
                    (0, exports.debug)("No valid license available in licensing wizard. Trying again in ".concat(retryTime, " seconds"));
                    wizardTimer = setTimeout(function () { return getlicenseFromWizard(licenseContext); }, retryTime * 1000);
                }
                else {
                    (0, exports.logInfo)("Got a valid license from local license wizard.");
                    checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
                }
                return [3 /*break*/, 4];
            case 3:
                checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard;
                (0, exports.debug)("No license available in licensing wizard. Trying again in ".concat(retryTime, " seconds"));
                wizardTimer = setTimeout(function () { return getlicenseFromWizard(licenseContext); }, retryTime * 1000);
                _b.label = 4;
            case 4: return [3 /*break*/, 6];
            case 5:
                err_3 = _b.sent();
                checkStatus = licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard;
                // Failed to connect.  Retry
                getLicenseFailCounts += 1;
                if (getLicenseFailCounts < maxretries) {
                    (0, exports.debug)("Could not find licensing wizard. Trying again in ".concat(retryTime, " seconds"));
                    wizardTimer = setTimeout(function () { return getlicenseFromWizard(licenseContext); }, retryTime * 1000);
                }
                else {
                    // give up.
                    console.log("Failed to connect to licensing wizard. Refresh page to retry.");
                    getLicenseFailCounts = 0;
                    checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToFindLicenseWizard;
                }
                return [3 /*break*/, 6];
            case 6:
                licenseInfo = (0, exports.getLicenseInfo)(licenseContext);
                if (licenseInfo.hasChanged) {
                    getAllSurfaces().forEach(function (sciChartSurface) {
                        updateLicenseDisplayInternal(licenseInfo, sciChartSurface, sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
                    });
                }
                return [2 /*return*/];
        }
    });
}); };
var setLicenseCookie = function (key, token, expirySeconds, lastValidated) {
    var cookieVal = "".concat(key, ",").concat(token, ",").concat(expirySeconds, ",").concat(lastValidated);
    return licenseDependencies.setCookie("scLicense", cookieVal, 365);
};
var getLicenseCookie = function () {
    var cookie;
    cookie = licenseDependencies.getCookie("scLicense");
    var parts = cookie.split(",");
    if (parts.length === 4)
        /// TODO worry about UTC here
        return {
            key: parts[0],
            token: parts[1],
            expiry: new Date(Number.parseInt(parts[2], 10) * 1000),
            lastValidated: new Date(Number.parseInt(parts[3], 10) * 1000)
        };
    else
        return { key: parts[0], token: null, expiry: null, lastValidated: null };
};
exports.getLicenseCookie = getLicenseCookie;
var getAllLicenseContexts = function () {
    var lcs = [];
    if (Globals_1.sciChartDestinations.length > 0) {
        lcs.push(Globals_1.sciChartDestinations[0].sciChartSurface.getLicenseContext());
    }
    if (Globals_1.sciChart3DDestinations.length > 0) {
        lcs.push(Globals_1.sciChart3DDestinations[0].sciChartSurface.getLicenseContext());
    }
    Globals_1.sciChartSingleDestinations.forEach(function (d) { return lcs.push(d.sciChartSurface.getLicenseContext()); });
    Globals_1.sciChart3DSingleDestinations.forEach(function (d) { return lcs.push(d.sciChartSurface.getLicenseContext()); });
    return lcs;
};
var getAllSurfaces = function () {
    var surfaces = [];
    Globals_1.sciChartDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
    Globals_1.sciChart3DDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
    Globals_1.sciChartSingleDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
    Globals_1.sciChart3DSingleDestinations.forEach(function (d) { return surfaces.push(d.sciChartSurface); });
    return surfaces;
};
var setChallengeResponse = function (token, licenseContext) {
    var expirySeconds = -1;
    expirySeconds = licenseContext.SCRTCredentials.ApplyLicenseResponse(token);
    getAllLicenseContexts().forEach(function (lc) { return lc.SCRTCredentials.ApplyLicenseResponse(token); });
    return expirySeconds;
};
var SIMPLE_RESPONSE_ERRORS = (_a = {},
    _a[-1] = "No client secret configured",
    _a[-2] = "Client secret missing ; separator",
    _a[-3] = "Pubkey in client secret is not valid 32-byte hex",
    _a[-4] = "Token does not match expected v2 field count",
    _a[-5] = "HMAC field is not exactly 64 hex chars",
    _a[-6] = "Server time field is not a valid integer",
    _a[-7] = "Token has expired",
    _a[-8] = "HMAC field contains non-hex characters",
    _a[-9] = "HMAC does not match — wrong signing key",
    _a[-11] = "Token has wrong field count, or licence requires round-trip (validate_nonce=1) and an inline token was received",
    _a[-12] = "Client-nonce in token does not match the nonce sent (round-trip mode)",
    _a[-13] = "Nonce reuse — token already seen this session",
    _a[-14] = "Server time has not progressed monotonically since last validation",
    _a[-15] = "Licence feature string malformed or out of range",
    _a[-16] = "Server / client clock skew exceeds licence-declared max_skew",
    _a);
var setSimpleChallengeResponse = function (token, licenseContext) {
    var _a;
    (0, exports.debug)("setSimpleChallengeResponse ".concat(token));
    var expirySeconds = licenseContext.SCRTCredentials.ApplySimpleResponse(token);
    getAllLicenseContexts().forEach(function (lc) { return lc.SCRTCredentials.ApplySimpleResponse(token); });
    if (expirySeconds < 0) {
        (0, exports.debug)("setSimpleChallengeResponse failed (".concat(expirySeconds, "): ").concat((_a = SIMPLE_RESPONSE_ERRORS[expirySeconds]) !== null && _a !== void 0 ? _a : "Unknown error"));
    }
    return expirySeconds;
};
var challengeFailCounts = 0;
var dolicenseChallenge = function (licenseContext) { return __awaiter(void 0, void 0, void 0, function () {
    var lcs, server, challenge, orderId, response, queryString, url, url, token, expirySeconds, key, timeNow, timeToExpiry, err_4, licenseInfo_1, expiry, msg, licenseInfo;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                lcs = getAllLicenseContexts();
                if (licenseContext === undefined) {
                    if (lcs.length > 0) {
                        licenseContext = lcs[0];
                    }
                    else {
                        return [2 /*return*/];
                    }
                }
                server = licenseManager2dState_1.licenseManager2dState.isDev ? "license wizard" : "server";
                _a.label = 1;
            case 1:
                _a.trys.push([1, 11, , 12]);
                if (!isValidating(checkStatus))
                    return [2 /*return*/];
                (0, exports.debug)("Attempting to validate license with ".concat(server));
                challenge = licenseContext.SCRTCredentials.GetLicenseChallenge();
                orderId = licenseContext.SCRTCredentials.GetOrderId();
                response = void 0;
                queryString = "orderid=".concat(orderId, "&challenge=").concat(challenge);
                if (!licenseManager2dState_1.licenseManager2dState.isDev) return [3 /*break*/, 3];
                url = "/validate?".concat(queryString);
                return [4 /*yield*/, licenseDependencies.fetchFromWizard(url)];
            case 2:
                response = _a.sent();
                return [3 /*break*/, 7];
            case 3:
                if (!(typeof licenseCallback !== "undefined")) return [3 /*break*/, 5];
                return [4 /*yield*/, licenseCallback(queryString)];
            case 4:
                response = _a.sent();
                return [3 /*break*/, 7];
            case 5:
                url = "/" + serverLicenseEndpoint + (serverLicenseEndpoint.indexOf("?") > 0 ? "&" : "?") + queryString;
                return [4 /*yield*/, licenseDependencies.fetchForChallenge(url)];
            case 6:
                response = _a.sent();
                _a.label = 7;
            case 7:
                if (!response.ok) return [3 /*break*/, 9];
                return [4 /*yield*/, response.text()];
            case 8:
                token = _a.sent();
                if (!token.startsWith("Error")) {
                    expirySeconds = setChallengeResponse(token, licenseContext);
                    if (expirySeconds > 0) {
                        key = (0, exports.getLicenseCookie)().key;
                        if (!key)
                            key = getRuntimeLicenseKey();
                        timeNow = Math.floor(new Date().getTime() / 1000);
                        setLicenseCookie(key, token, expirySeconds, timeNow);
                        (0, exports.logInfo)("License validated");
                        checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
                        timeToExpiry = expirySeconds - timeNow;
                        challengeFailCounts = 0;
                        licenseChallengeTimeout = setTimeout(function () {
                            checkStatus = validatingStatus();
                            // Only refresh chart when we have a valid license
                            licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
                            dolicenseChallenge(undefined);
                        }, Math.floor(timeToExpiry * 0.95 * 1000)); // Allow 5%
                    }
                    else {
                        // Something went wrong with the apply
                        (0, exports.logInfo)("license challenge response was invalid: ".concat(token, " ").concat(expirySeconds));
                        checkStatus = failedValidateStatus();
                    }
                }
                else {
                    // Challenge rejected by server
                    (0, exports.logInfo)("Server rejected the license challenge: " + token);
                    checkStatus = failedValidateStatus();
                }
                return [3 /*break*/, 10];
            case 9:
                // Server error or network failure
                if (licenseManager2dState_1.licenseManager2dState.isDev) {
                    console.warn("Error during license validation: " + response.statusText);
                    checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateDeveloperLicense;
                }
                else {
                    // switch to license wizard
                    throw new Error(response.statusText);
                }
                _a.label = 10;
            case 10: return [3 /*break*/, 12];
            case 11:
                err_4 = _a.sent();
                // switch to license wizard
                if (!licenseManager2dState_1.licenseManager2dState.isDev) {
                    console.warn("Server license validation failed.  Looking for local developer license");
                    runtimeLicenseKey = "";
                    checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
                    licenseContext.SCRTCredentials.ResetRuntimeLicense();
                    lcs.forEach(function (lc) { return lc.SCRTCredentials.ResetRuntimeLicense(); });
                    isRuntimeKey = false;
                    licenseManager2dState_1.licenseManager2dState.isDev = true;
                    checkStatus = licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard;
                    licenseInfo_1 = (0, exports.getLicenseInfo)(licenseContext);
                    if (licenseInfo_1.hasChanged) {
                        getAllSurfaces().forEach(function (sciChartSurface) {
                            updateLicenseDisplayInternal(licenseInfo_1, sciChartSurface, sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
                        });
                    }
                    getlicenseFromWizard(licenseContext);
                    return [2 /*return*/];
                }
                // Failed to connect.  Retry
                challengeFailCounts += 1;
                if (challengeFailCounts < maxretries) {
                    (0, exports.debug)("Could not find ".concat(server, "/").concat(serverLicenseEndpoint, ". Trying again in ").concat(retryTime, " seconds"));
                    licenseChallengeTimeout = setTimeout(function () { return dolicenseChallenge(licenseContext); }, retryTime * 1000);
                }
                else {
                    expiry = (0, exports.getLicenseCookie)().expiry;
                    msg = licenseManager2dState_1.licenseManager2dState.isDev
                        ? "Please run the license wizard, ensure your license is activated, then refresh page to retry."
                        : "Please check that the endpoint is configured correctly.";
                    console.error("Failed to connect to ".concat(server, "/").concat(serverLicenseEndpoint, ".  ").concat(msg));
                    if (expiry) {
                        console.warn("License must be revalidated before ".concat(expiry.toLocaleString(), "."));
                    }
                    challengeFailCounts = 0;
                    // Only actually show failure message if token has expired
                    if (new Date() > expiry)
                        checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToFindLicenseWizard;
                }
                return [3 /*break*/, 12];
            case 12:
                licenseInfo = (0, exports.getLicenseInfo)(licenseContext);
                if (licenseInfo.hasChanged) {
                    getAllSurfaces().forEach(function (sciChartSurface) {
                        updateLicenseDisplayInternal(licenseInfo, sciChartSurface, sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
                    });
                }
                return [2 /*return*/];
        }
    });
}); };
var doSimpleLicenseChallenge = function (licenseContext) { return __awaiter(void 0, void 0, void 0, function () {
    var lcs, orderId, inlineToken, applyValidatedToken, expirySeconds, credentials, queryString, clientNonce, response, url, token, expirySeconds, err_5, expiry, licenseInfo;
    var _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                lcs = getAllLicenseContexts();
                if (licenseContext === undefined) {
                    if (lcs.length > 0)
                        licenseContext = lcs[0];
                    else
                        return [2 /*return*/];
                }
                _b.label = 1;
            case 1:
                _b.trys.push([1, 10, , 11]);
                if (!isValidating(checkStatus))
                    return [2 /*return*/];
                (0, exports.debug)("Attempting simple server license validation");
                orderId = licenseContext.SCRTCredentials.GetOrderId();
                inlineToken = licenseDependencies.generateSimpleToken(orderId);
                applyValidatedToken = function (token, expirySeconds) {
                    var key = (0, exports.getLicenseCookie)().key;
                    if (!key)
                        key = getRuntimeLicenseKey();
                    var timeNow = Math.floor(new Date().getTime() / 1000);
                    setLicenseCookie(key, token, expirySeconds, timeNow);
                    (0, exports.logInfo)("Simple server license validated");
                    checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
                    challengeFailCounts = 0;
                    var timeToExpiry = expirySeconds - timeNow;
                    licenseChallengeTimeout = setTimeout(function () {
                        checkStatus = licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
                        licenseManager2dState_1.licenseManager2dState.checkStatus = licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey;
                        doSimpleLicenseChallenge(undefined);
                    }, Math.floor(timeToExpiry * 0.95 * 1000));
                };
                if (!(inlineToken !== null)) return [3 /*break*/, 2];
                if (!inlineToken.startsWith("Error")) {
                    expirySeconds = setSimpleChallengeResponse(inlineToken, licenseContext);
                    if (expirySeconds > 0) {
                        applyValidatedToken(inlineToken, expirySeconds);
                    }
                    else {
                        (0, exports.logInfo)("Simple license response was invalid: ".concat(inlineToken, " ").concat(expirySeconds));
                        checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
                    }
                }
                else {
                    (0, exports.logInfo)("Simple license token error: " + inlineToken);
                    checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
                }
                return [3 /*break*/, 9];
            case 2:
                credentials = licenseContext.SCRTCredentials;
                queryString = "orderid=".concat(orderId);
                if (((_a = credentials.IsRoundTripValidation) === null || _a === void 0 ? void 0 : _a.call(credentials)) && credentials.GenerateClientNonce) {
                    clientNonce = credentials.GenerateClientNonce();
                    queryString += "&nonce=".concat(encodeURIComponent(clientNonce));
                    (0, exports.debug)("Round-trip mode: included client nonce in request");
                }
                response = void 0;
                if (!(typeof licenseCallback !== "undefined")) return [3 /*break*/, 4];
                return [4 /*yield*/, licenseCallback(queryString)];
            case 3:
                response = _b.sent();
                return [3 /*break*/, 6];
            case 4:
                url = "/" + serverLicenseEndpoint +
                    (serverLicenseEndpoint.indexOf("?") > 0 ? "&" : "?") + queryString;
                return [4 /*yield*/, licenseDependencies.fetchForChallenge(url)];
            case 5:
                response = _b.sent();
                _b.label = 6;
            case 6:
                if (!response.ok) return [3 /*break*/, 8];
                return [4 /*yield*/, response.text()];
            case 7:
                token = _b.sent();
                if (!token.startsWith("Error")) {
                    expirySeconds = setSimpleChallengeResponse(token, licenseContext);
                    if (expirySeconds > 0) {
                        applyValidatedToken(token, expirySeconds);
                    }
                    else {
                        (0, exports.logInfo)("Simple license response was invalid: ".concat(token, " ").concat(expirySeconds));
                        checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
                    }
                }
                else {
                    (0, exports.logInfo)("Server rejected simple license request: " + token);
                    checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
                }
                return [3 /*break*/, 9];
            case 8: throw new Error(response.statusText);
            case 9: return [3 /*break*/, 11];
            case 10:
                err_5 = _b.sent();
                challengeFailCounts += 1;
                if (challengeFailCounts < maxretries) {
                    (0, exports.debug)("Could not reach /".concat(serverLicenseEndpoint, ". Retrying in ").concat(retryTime, "s"));
                    licenseChallengeTimeout = setTimeout(function () { return doSimpleLicenseChallenge(licenseContext); }, retryTime * 1000);
                }
                else {
                    expiry = (0, exports.getLicenseCookie)().expiry;
                    console.error("Failed to connect to /".concat(serverLicenseEndpoint, ". Please check the endpoint is configured correctly."));
                    if (expiry)
                        console.warn("License must be revalidated before ".concat(expiry.toLocaleString(), "."));
                    challengeFailCounts = 0;
                    if (new Date() > expiry)
                        checkStatus = licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey;
                }
                return [3 /*break*/, 11];
            case 11:
                licenseInfo = (0, exports.getLicenseInfo)(licenseContext);
                if (licenseInfo.hasChanged) {
                    getAllSurfaces().forEach(function (s) {
                        return updateLicenseDisplayInternal(licenseInfo, s, s.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType);
                    });
                }
                return [2 /*return*/];
        }
    });
}); };
var checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
var isRuntimeKey = false;
var communityNotice = false;
var applyLicense = function (licenseContext, source) {
    var _a, _b;
    (0, exports.debug)("applyLicense from " + source);
    var licenseKey = "";
    var lt = licenseContext.SCRTCredentials.GetLicenseType();
    (0, exports.logInfo)("Initial license status is " + licensingClasses_1.LicenseType[convertLicenseType(lt, licenseContext)]);
    // Get from global store
    var runtimelicense = getRuntimeLicenseKey();
    if ((checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicense ||
        checkStatus === licensingClasses_1.LicenseCheckStatus.LicenseOK ||
        checkStatus === licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard ||
        checkStatus === licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard) &&
        //lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY &&
        runtimelicense) {
        (0, exports.logInfo)("Runtime license found");
        (0, exports.debug)("runtime license length=".concat(runtimelicense.length, " hash=").concat(hashLicenseKey(runtimelicense), " value=").concat(runtimelicense));
        var sep = runtimelicense.indexOf(";");
        if (sep > 0) {
            var timeNow = Math.floor(new Date().getTime() / 1000);
            var token = runtimelicense.substring(sep + 1);
            setLicenseCookie(runtimelicense.substr(0, sep), token, timeNow + 60, timeNow);
        }
        else {
            licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(runtimelicense);
            lt = licenseContext.SCRTCredentials.GetLicenseType();
            var licenseType = convertLicenseType(lt, licenseContext);
            (0, exports.logInfo)("Runtime license status is " + licensingClasses_1.LicenseType[licenseType]);
            if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
                lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL ||
                lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY ||
                lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_REQUIRES_VALIDATION) {
                isRuntimeKey = true;
                licenseKey = runtimelicense;
            }
            else {
                var errorMsg = licenseContext.SCRTCredentials.GetLicenseErrors();
                (0, exports.logInfo)("Runtime license is invalid: " + errorMsg);
                licenseKey = "";
            }
        }
    }
    // Get from cookie store
    var licenseCookie = (0, exports.getLicenseCookie)();
    if (licenseKey === "" && licenseCookie && licenseCookie.key !== "") {
        (0, exports.logInfo)("Found license in cookie.");
        licenseKey = licenseCookie.key;
        licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(licenseKey);
        lt = licenseContext.SCRTCredentials.GetLicenseType();
        // if the license in cookie is bad, remove it
        if (!(lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
            lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL ||
            lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_REQUIRES_VALIDATION)) {
            (0, exports.logInfo)("License cookie is invalid. " + licenseContext.SCRTCredentials.GetLicenseErrors());
            (0, cookie_1.deleteCookie)("scLicense");
            licenseKey = "";
            lt = licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY;
        }
    }
    else if (checkStatus === licensingClasses_1.LicenseCheckStatus.FetchingFromServer) {
        checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
    }
    if (licenseKey !== "") {
        if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY) {
            // Set the license if we haven't already
            licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(licenseKey);
            lt = licenseContext.SCRTCredentials.GetLicenseType();
        }
        licenseManager2dState_1.licenseManager2dState.isDev = licenseContext.SCRTCredentials.GetAllowDebugging();
        if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
            lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL ||
            lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY) {
            checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
            (0, exports.logInfo)("license ok");
            if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY && isRuntimeKey && !communityNotice) {
                console.log("Using SciChart Community Edition. To use a license from the License Wizard, remove the call to UseCommunityLicense");
                var daysRemaining = licenseContext.SCRTCredentials.GetLicenseDaysRemaining();
                console.log("The community license is valid for 6 months from the date the version in use was released.  This version ".concat(BuildStamp_1.libraryVersion, " has ").concat(daysRemaining, " day").concat(daysRemaining === 1 ? "" : "s", " remaining"));
                communityNotice = true;
            }
        }
        else if (licenseContext.SCRTCredentials.RequiresValidation()) {
            (0, exports.logInfo)("license requires validation");
            var metaToken = null;
            if (licenseContext.SCRTCredentials.IsSimpleValidation()) {
                try {
                    metaToken = licenseDependencies.getInitialToken();
                }
                catch (_) {
                    metaToken = null;
                }
            }
            if (isRuntimeKey && licenseManager2dState_1.licenseManager2dState.isDev) {
                // clear key
                licenseContext.SCRTCredentials.ResetRuntimeLicense();
                (0, cookie_1.deleteCookie)("scLicense");
                checkStatus = licensingClasses_1.LicenseCheckStatus.DevKeyInRuntimeKey;
            }
            else if (metaToken !== null || (licenseCookie.expiry > new Date() && licenseCookie.key === licenseKey)) {
                var token = metaToken !== null && metaToken !== void 0 ? metaToken : licenseCookie.token;
                (0, exports.debug)(metaToken !== null ? "token from page meta tag" : "current token in cookie");
                var expirySeconds = licenseContext.SCRTCredentials.IsSimpleValidation()
                    ? setSimpleChallengeResponse(token, licenseContext)
                    : setChallengeResponse(token, licenseContext);
                lt = licenseContext.SCRTCredentials.GetLicenseType();
                if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
                    lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL) {
                    checkStatus = licensingClasses_1.LicenseCheckStatus.LicenseOK;
                }
                var timeNow = Math.floor(new Date().getTime() / 1000);
                if (metaToken !== null && expirySeconds <= 0) {
                    (0, exports.logInfo)("Meta-tag license token was rejected (".concat(expirySeconds, "): ").concat((_a = SIMPLE_RESPONSE_ERRORS[expirySeconds]) !== null && _a !== void 0 ? _a : "Unknown error"));
                    checkStatus = failedValidateStatus();
                }
                else {
                    if (metaToken !== null || expirySeconds * 1000 > licenseCookie.expiry.getTime()) {
                        setLicenseCookie(licenseKey, token, expirySeconds, timeNow);
                    }
                    // Force re-validation at most once a day, or sooner if the
                    // licence's valid_time is shorter than that (cap at the token's
                    // own validity duration so a 30-min licence still re-validates
                    // within its window rather than waiting 24h).
                    // Meta-token path: the cookie is being written this tick (line above) with timeNow
                    // as lastValidated, but the in-memory licenseCookie snapshot is still pre-write
                    // (and lastValidated can be null if no prior cookie existed). Use timeNow to
                    // reflect the value about to be persisted.
                    var lastValidatedSec = metaToken !== null
                        ? timeNow
                        : Math.floor(licenseCookie.lastValidated.getTime() / 1000);
                    var validityDuration = Math.max(0, expirySeconds - lastValidatedSec);
                    var validationInterval = Math.min(60 * 60 * 24, validityDuration);
                    var secondsSinceValidated = metaToken !== null ? 0 : (new Date().getTime() - licenseCookie.lastValidated.getTime()) / 1000;
                    (0, exports.debug)("License expires in ".concat(expirySeconds - timeNow, " seconds.  Last validated ").concat(secondsSinceValidated, " seconds ago"));
                    if (secondsSinceValidated > validationInterval &&
                        !isValidating(checkStatus)) {
                        // revalidate now
                        checkStatus = validatingStatus();
                        licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
                        if (licenseContext.SCRTCredentials.IsSimpleValidation() && !licenseManager2dState_1.licenseManager2dState.isDev) {
                            doSimpleLicenseChallenge(licenseContext);
                        }
                        else {
                            dolicenseChallenge(licenseContext);
                        }
                    }
                    else if (licenseChallengeTimeout === undefined) {
                        // set timer to revaildate later
                        licenseChallengeTimeout = setTimeout(function () {
                            checkStatus = validatingStatus();
                            // Only refresh chart when we have a valid license
                            licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
                            if (licenseContext.SCRTCredentials.IsSimpleValidation() && !licenseManager2dState_1.licenseManager2dState.isDev) {
                                doSimpleLicenseChallenge(undefined);
                            }
                            else {
                                dolicenseChallenge(undefined);
                            }
                        }, Math.floor((expirySeconds - timeNow) * 0.95 * 1000)); // Allow 5%
                    }
                }
            }
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicense) {
                checkStatus = validatingStatus();
                if (licenseContext.SCRTCredentials.IsSimpleValidation() && !licenseManager2dState_1.licenseManager2dState.isDev) {
                    doSimpleLicenseChallenge(licenseContext);
                }
                else {
                    dolicenseChallenge(licenseContext);
                }
            }
        }
        else {
            (0, exports.logInfo)("license is invalid: " + licenseContext.SCRTCredentials.GetLicenseErrors());
        }
    }
    (0, exports.logInfo)("checkstatus: " + licensingClasses_1.LicenseCheckStatus[checkStatus]);
    if (checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicense) {
        if (lt === licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY && !communityNotice) {
            console.log("Defaulting to SciChart Community Edition. Usage constitutes acceptance of our EULA and terms at https://www.scichart.com/community-licensing. See https://store.scichart.com for commercial licensing options.");
            var daysRemaining = licenseContext.SCRTCredentials.GetLicenseDaysRemaining();
            console.log("The community license is valid for 6 months from the date the version in use was released.  This version ".concat(BuildStamp_1.libraryVersion, " has ").concat(daysRemaining, " day").concat(daysRemaining === 1 ? "" : "s", " remaining"));
            if (!app_1.IS_TEST_ENV && ((_b = document === null || document === void 0 ? void 0 : document.location) === null || _b === void 0 ? void 0 : _b.hostname.startsWith("localhost")) && useLicenseWizard) {
                console.log("SciChart is looking for a paid developer activation from the scichart licensing wizard... To disable this call SciChartSurface.UseCommunityLicense()");
            }
            communityNotice = true;
        }
        if (wizardTimer === undefined && useLicenseWizard) {
            checkStatus = licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard;
            licenseManager2dState_1.licenseManager2dState.isDev = true;
            getlicenseFromWizard(licenseContext);
        }
    }
};
exports.applyLicense = applyLicense;
var licenseModal;
var openLicenseModal = function () {
    console.error("Modal not initialized");
};
var setNewLicense = function (keyCode, licenseContext) {
    var requiresValidation = false;
    var trialExpired;
    if (licenseModal) {
        licenseModal.style.display = "none";
    }
    isRuntimeKey = false;
    setLicenseCookie(keyCode, null, null, null);
    licenseContext.SCRTCredentials.SetRuntimeLicenseKeyW(keyCode);
    requiresValidation = licenseContext.SCRTCredentials.RequiresValidation();
    trialExpired = licenseContext.SCRTCredentials.GetLicenseType() === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL_EXPIRED;
    getAllLicenseContexts().forEach(function (lc) { return lc.SCRTCredentials.SetRuntimeLicenseKeyW(keyCode); });
    return { requiresValidation: requiresValidation, trialExpired: trialExpired };
};
var insertedRules = new Dictionary_1.Dictionary();
var insertStyleSheetRule = function (ruleName, ruleText) {
    if (insertedRules.containsKey(ruleName))
        return;
    var sheets = document.styleSheets;
    if (sheets.length === 0) {
        var style = document.createElement("style");
        style.appendChild(document.createTextNode(""));
        document.head.appendChild(style);
    }
    var sheet = sheets[sheets.length - 1];
    // @ts-ignore
    var index = sheet.insertRule(ruleText, sheet.cssRules.length);
    insertedRules.add(ruleName, index);
};
var createCloseDivStyles = function () {
    insertStyleSheetRule("licenseModalClose", ".licenseModalClose {\n        color: #aaa;\n        float: right;\n        font-size: 28px;\n        font-weight: bold;\n      }");
    insertStyleSheetRule("licenseModalClose:hover", ".licenseModalClose:hover {\n        color: black;\n        text-decoration: none;\n        cursor: pointer;\n      }");
    insertStyleSheetRule("licenseModalClose:focus", ".licenseModalClose:focus {\n        color: black;\n        text-decoration: none;\n        cursor: pointer;\n      }");
};
var fallbackCopy = function (text) {
    var ta = document.createElement("textarea");
    ta.value = text;
    ta.style.position = "fixed";
    ta.style.opacity = "0";
    document.body.appendChild(ta);
    ta.select();
    document.execCommand("copy");
    document.body.removeChild(ta);
};
var createLicenseModal = function (message, postFormMessage) {
    licenseModal = document.createElement("div");
    licenseModal.id = "scichartLicenseModal";
    licenseModal.style.display = "none"; /* Hidden by default */
    licenseModal.style.position = "fixed"; /* Stay in place */
    licenseModal.style.zIndex = "100"; /* Sit on top */
    licenseModal.style.left = "0";
    licenseModal.style.top = "0";
    licenseModal.style.width = "100%"; /* Full width */
    licenseModal.style.height = "100%"; /* Full height */
    licenseModal.style.overflow = "auto"; /* Enable scroll if needed */
    licenseModal.style.backgroundColor = "rgb(0,0,0)"; /* Fallback color */
    licenseModal.style.backgroundColor = "rgba(0,0,0,0.4)"; /* Black w/ opacity */
    var modalContent = document.createElement("div");
    modalContent.style.backgroundColor = "#fefefe";
    modalContent.style.position = "absolute";
    modalContent.style.left = "50%";
    modalContent.style.top = "50%";
    modalContent.style.transform = "translate(-50%, -50%)";
    modalContent.style.borderRadius = "4px";
    modalContent.style.padding = "20px";
    modalContent.style.maxWidth = "460px";
    licenseModal.appendChild(modalContent);
    var modalContentForm = document.createElement("div");
    modalContentForm.style.display = "block";
    modalContent.appendChild(modalContentForm);
    var modalContentMessage = document.createElement("div");
    modalContentMessage.style.display = "none";
    modalContent.appendChild(modalContentMessage);
    openLicenseModal = function () {
        licenseModal.style.display = "block";
        modalContentForm.style.display = "block";
        modalContentMessage.style.display = "none";
    };
    var modalHeader = document.createElement("div");
    modalHeader.style.display = "flex";
    modalHeader.style.padding = "8px 16px";
    modalHeader.style.backgroundColor = "#5cb85c";
    modalHeader.style.color = "white";
    modalContentForm.appendChild(modalHeader);
    var modalHeaderTitle = document.createElement("div");
    modalHeaderTitle.style.flexGrow = "1";
    modalHeaderTitle.innerHTML = message;
    modalHeader.appendChild(modalHeaderTitle);
    createCloseDivStyles();
    var closeDiv = document.createElement("span");
    closeDiv.innerHTML = "&times;";
    closeDiv.className = "licenseModalClose";
    modalHeader.appendChild(closeDiv);
    var buttonLabel = document.createElement("div");
    buttonLabel.innerHTML = "If you contact support with a licensing issue, please send us the license log.\n    Use 'Show license log' below to view and copy collected log entries.\n    For more detailed output, enable debug mode and reload.";
    var toggleDebugModeButton = document.createElement("button");
    toggleDebugModeButton.style.margin = "10px";
    var setDebugModeSwitchLabel = function () {
        toggleDebugModeButton.textContent = isDebug ? "Disable licensing debug mode" : "Enable licensing debug mode";
    };
    setDebugModeSwitchLabel();
    toggleDebugModeButton.onclick = function () {
        (0, exports.setIsDebugLicensing)(!isDebug, true);
        setDebugModeSwitchLabel();
    };
    modalContentForm.appendChild(buttonLabel);
    modalContentForm.appendChild(toggleDebugModeButton);
    var showLogButton = document.createElement("button");
    showLogButton.textContent = "Show license log";
    showLogButton.style.margin = "10px";
    var logContainer = document.createElement("div");
    logContainer.style.display = "none";
    logContainer.style.margin = "0 10px 10px 10px";
    var logPre = document.createElement("pre");
    logPre.style.maxHeight = "200px";
    logPre.style.overflow = "auto";
    logPre.style.background = "#f4f4f4";
    logPre.style.padding = "8px";
    logPre.style.fontSize = "11px";
    logPre.style.fontFamily = "monospace";
    logPre.style.textAlign = "left";
    logPre.style.color = "#333";
    logPre.style.whiteSpace = "pre-wrap";
    logPre.style.wordBreak = "break-all";
    logContainer.appendChild(logPre);
    var copyLogButton = document.createElement("button");
    copyLogButton.textContent = "Copy to clipboard";
    copyLogButton.style.margin = "5px 0";
    copyLogButton.onclick = function () {
        var text = formatLicenseLog() || "(no log entries)";
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).catch(function () { return fallbackCopy(text); });
        }
        else {
            fallbackCopy(text);
        }
    };
    logContainer.appendChild(copyLogButton);
    showLogButton.onclick = function () {
        if (logContainer.style.display === "none") {
            logPre.textContent = formatLicenseLog() || "(no log entries)";
            logContainer.style.display = "block";
            showLogButton.textContent = "Hide license log";
        }
        else {
            logContainer.style.display = "none";
            showLogButton.textContent = "Show license log";
        }
    };
    modalContentForm.appendChild(showLogButton);
    modalContentForm.appendChild(logContainer);
    var modalFooter = document.createElement("div");
    modalFooter.innerHTML = postFormMessage;
    modalFooter.style.padding = "8px 16px";
    modalFooter.style.backgroundColor = "#5cb85c";
    modalFooter.style.color = "white";
    modalContentForm.appendChild(modalFooter);
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target === licenseModal) {
            licenseModal.style.display = "none";
        }
    };
    var oldModal = document.querySelector("[id='".concat(licenseModal.id, "']"));
    if (oldModal == null)
        document.body.appendChild(licenseModal);
    else
        document.body.replaceChild(licenseModal, oldModal);
    // When the user clicks on <div> (x), close the modal
    closeDiv.onclick = function () {
        licenseModal.style.display = "none";
    };
    return licenseModal;
};
var LICENSE_MSG_CLASS = "licenseMessage";
var LICENSE_MSG_CLASS_CHILD = "licenseMessageChild";
var licenseMessageDiv = null;
var licenseMessageDivChild = null;
var updateLicenseMessageDOM = function (divContainer, licenseMsgDiv) {
    if (!divContainer) {
        return;
    }
    var msgCloneOther = licenseMsgDiv.cloneNode(true);
    // find the immediate child license message div
    var lm = Array.from(divContainer.children).find(function (el) { return el.className === LICENSE_MSG_CLASS; });
    if (lm) {
        divContainer.replaceChild(msgCloneOther, lm);
    }
    else {
        divContainer.appendChild(msgCloneOther);
    }
    if (useLicenseWizard)
        msgCloneOther.onclick = openLicenseModal;
};
var convertLicenseType = function (sclt, licenseContext) {
    var licenseType = licensingClasses_1.LicenseType.NoLicense;
    switch (sclt) {
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_NO_LICENSE: {
            licenseType = licensingClasses_1.LicenseType.NoLicense;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL: {
            licenseType = licensingClasses_1.LicenseType.Trial;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_COMMUNITY: {
            licenseType = licensingClasses_1.LicenseType.Community;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL: {
            licenseType = licensingClasses_1.LicenseType.Full;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL_EXPIRED: {
            licenseType = licensingClasses_1.LicenseType.Full_Expired;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL_EXPIRED: {
            licenseType = licensingClasses_1.LicenseType.Trial_Expired;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_SUBSCRIPTION_EXPIRED: {
            licenseType = licensingClasses_1.LicenseType.Subscription_Expired;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_INVALID_DEVELOPER_LICENSE: {
            licenseType = licensingClasses_1.LicenseType.Invalid_Developer;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_REQUIRES_VALIDATION: {
            licenseType = licensingClasses_1.LicenseType.Requres_Validation;
            break;
        }
        case licenseContext.SCRTLicenseType.LICENSE_TYPE_INVALID_LICENSE: {
            licenseType = licensingClasses_1.LicenseType.Invalid;
            break;
        }
    }
    return licenseType;
};
var getLicenseInfo = function (licenseContext) {
    var sclt = licenseContext.SCRTCredentials.GetLicenseType();
    var licenseType = convertLicenseType(sclt, licenseContext);
    var daysRemaining = licenseContext.SCRTCredentials.GetLicenseDaysRemaining();
    var hasChanged = false;
    if (checkStatus !== licenseManager2dState_1.licenseManager2dState.checkStatus ||
        licenseType !== licenseManager2dState_1.licenseManager2dState.licenseType) {
        hasChanged = true;
        (0, exports.logInfo)("License status updated ".concat(licensingClasses_1.LicenseCheckStatus[checkStatus], " ").concat(licensingClasses_1.LicenseType[licenseType]));
        if (licenseType === licensingClasses_1.LicenseType.Community) {
            licenseManager2dState_1.licenseManager2dState.orderId = "Community";
        }
        else {
            licenseManager2dState_1.licenseManager2dState.orderId = licenseContext.SCRTCredentials.GetEncryptedOrderId();
        }
        licenseManager2dState_1.licenseManager2dState.productCode = licenseContext.SCRTCredentials.GetProductCode();
        licenseManager2dState_1.licenseManager2dState.licenseType = licenseType;
        licenseManager2dState_1.licenseManager2dState.checkStatus = checkStatus;
        licenseManager2dState_1.licenseManager2dState.devCount = licenseContext.SCRTCredentials.GetDeveloperCount();
        var licenseType3D = convertLicenseType(licenseContext.SCRTCredentials.HasFeature("JS-3D"), licenseContext);
        if (licenseType !== licensingClasses_1.LicenseType.Full && licenseType !== licensingClasses_1.LicenseType.Trial) {
            licenseType3D = licenseType;
        }
        licenseManager2dState_1.licenseManager2dState.licenseType3D = licenseType3D;
        var error = licenseContext.SCRTCredentials.GetLicenseErrors();
        licenseManager2dState_1.licenseManager2dState.error = error;
        // Telemetry is enabled based on a license feature
        var teFeature = licenseContext.SCRTCredentials.HasFeature("TE");
        licenseManager2dState_1.licenseManager2dState.telemetryEnabled =
            teFeature === licenseContext.SCRTLicenseType.LICENSE_TYPE_FULL ||
                teFeature === licenseContext.SCRTLicenseType.LICENSE_TYPE_TRIAL;
        if (isDebug) {
            (0, exports.debug)(licenseContext.SCRTCredentials.Dump());
        }
    }
    return { hasChanged: hasChanged, licenseType: licenseType, licenseType3D: licenseManager2dState_1.licenseManager2dState.licenseType3D, daysRemaining: daysRemaining, error: licenseManager2dState_1.licenseManager2dState.error };
};
exports.getLicenseInfo = getLicenseInfo;
var updateLicenseDisplayInternal = function (licenseInfo, sciChartSurface, is2D, forceDisplay) {
    var _a;
    if (forceDisplay === void 0) { forceDisplay = false; }
    if (licenseMessageDiv == null) {
        licenseMessageDiv = document.createElement("div");
        licenseMessageDiv.className = LICENSE_MSG_CLASS;
        licenseMessageDivChild = document.createElement("div");
        licenseMessageDivChild.className = LICENSE_MSG_CLASS_CHILD;
        licenseMessageDivChild.innerHTML = "";
        licenseMessageDiv.appendChild(licenseMessageDivChild);
    }
    var premsg = "";
    var chartmsg = "";
    var postMsg = "";
    var hasChanged = licenseInfo.hasChanged, licenseType = licenseInfo.licenseType, licenseType3D = licenseInfo.licenseType3D, daysRemaining = licenseInfo.daysRemaining, error = licenseInfo.error;
    if (hasChanged || forceDisplay ||
        (checkStatus == licensingClasses_1.LicenseCheckStatus.LicenseOK && licenseType !== licenseType3D)) {
        (0, exports.debug)("updateLicenseDisplay for ".concat((_a = sciChartSurface.domChartRoot) === null || _a === void 0 ? void 0 : _a.id));
        var currLicenseType = is2D ? licenseType : licenseType3D;
        // if (licenseType === LicenseType.Trial || licenseType === LicenseType.Full)
        //    checkStatus = LicenseCheckStatus.LicenseOK;
        sciChartSurface.invalidateElement();
        if (currLicenseType === licensingClasses_1.LicenseType.Community && checkStatus === licensingClasses_1.LicenseCheckStatus.StartLookingForLicenseWizard) {
            return;
        }
        var invalid3D = !is2D && licenseType !== licenseType3D;
        // Update license message text
        var licensingLink = "<a href=\"https://www.scichart.com/licensing-scichart-js\"  target=\"_blank\" style=\"color: white\">www.scichart.com/licensing-scichart-js</a>";
        var contactSupportLink = "<a href=\"https://www.scichart.com/contact-us/\"  target=\"_blank\" style=\"color: orange\">contact support</a>";
        if (currLicenseType === licensingClasses_1.LicenseType.NoLicense) {
            premsg = "You need to have a license to use SciChart.  ";
            postMsg = "Instructions can be seen at ".concat(licensingLink);
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Invalid) {
            if (error.startsWith("License is not valid for this domain"))
                premsg = "Sorry! The runtime license key is not valid for this domain</br>\n                Please ".concat(contactSupportLink, " with your OrderID if you believe this to be incorrect. <u>Click for more information</u></br>\n                For local development, make sure the Licensing Wizard is running and activated.</br>\n                To use Community Edition, remove the call to setRuntimeLicenseKey");
            else if (error.startsWith("This version of SciChart can no longer be trialed"))
                premsg = "Sorry! This version of SciChart is too old to be trialed.  Please update to the latest version";
            else if (error.startsWith("This version of SciChart can no longer be used for the community edition"))
                premsg = "Sorry! This version of SciChart is too old to be used for the community edition.  Please update to the latest version";
            else if (invalid3D)
                premsg = "Sorry! Your license is for ".concat(licenseManager2dState_1.licenseManager2dState.productCode, " which does not support 3D Charts.");
            else
                premsg = "Sorry! Your license key appears to be invalid</br>Please ".concat(contactSupportLink, " with your OrderID if you believe this to be incorrect.");
            postMsg = "Instructions can be seen at ".concat(licensingLink);
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Invalid_Developer) {
            premsg = "Sorry! You need a developer license to use SciChart on a domain not included in your runtime key.";
            postMsg = "Instructions can be seen at ".concat(licensingLink, "</br>\n                    Please ").concat(contactSupportLink, " with your OrderID if you are experiencing issues.");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Requres_Validation) {
            if (licenseManager2dState_1.licenseManager2dState.isDev) {
                premsg = "Your developer license must be validated by the SciChart Licensing Wizard running locally";
            }
            else {
                premsg = "This runtime key must be validated by a server side key.";
            }
            postMsg = "Instructions can be seen at ".concat(licensingLink, "</br>\n                    Please ").concat(contactSupportLink, " with your OrderID if you are experiencing issues.");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Subscription_Expired) {
            premsg = "Sorry! Your support subscription has expired.<br>";
            postMsg = "Please ".concat(contactSupportLink, " if you would like to renew your subscription.");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Trial_Expired && daysRemaining < 1) {
            premsg = "Sorry! Your trial has expired.";
            postMsg = "Please ".concat(contactSupportLink, " if you require an extension.");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Trial_Expired && daysRemaining > 1) {
            premsg = "This version is too old to trial.";
            postMsg = "Please ".concat(contactSupportLink, " if you require an extension.");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Trial && daysRemaining <= 7) {
            premsg = "You have ".concat(daysRemaining, " day").concat(daysRemaining === 1 ? "" : "s", " remaining of the trial.");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Community && daysRemaining <= 7) {
            premsg = "You have ".concat(daysRemaining, " day").concat(daysRemaining === 1 ? "" : "s", " remaining on the community license for this version.  Please update to the latest version of SciChart");
        }
        else if (currLicenseType === licensingClasses_1.LicenseType.Full ||
            ((currLicenseType === licensingClasses_1.LicenseType.Trial || currLicenseType === licensingClasses_1.LicenseType.Community) && daysRemaining > 7)) {
            licenseMessageDiv.style.display = "none";
            licenseMessageDivChild.innerHTML = "";
        }
        if (checkStatus !== licensingClasses_1.LicenseCheckStatus.LicenseOK || invalid3D) {
            if (checkStatus === licensingClasses_1.LicenseCheckStatus.FetchingFromServer) {
                chartmsg = "<br>Fetching license from server...";
            }
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.LookingForLicenseWizard) {
                if (currLicenseType === licensingClasses_1.LicenseType.Community) {
                    (0, Telemetry_1.sendTelemetry)();
                }
                chartmsg = "<br>Looking for Licensing Wizard...";
            }
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.FailedToFindLicenseWizard)
                if (licenseManager2dState_1.licenseManager2dState.isDev) {
                    chartmsg = "<br><u>Could not connect to the Licensing Wizard.  Please run it, then reload this page.</u>";
                }
                else {
                    chartmsg = "<br><u>Could not connect to the server licensing endpoint</u>";
                }
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.ValidatingDeveloperLicense)
                chartmsg = "<br><u>Trying to validate your license...";
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.ValidatingRuntimeKey)
                chartmsg = "<br><u>Trying to validate your license with the server...</u>.";
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.FailedToValidateDeveloperLicense)
                chartmsg = "<br><u>Failed to validate your developer license with the Licensing Wizard.  If you have changed your activated license, try clearing your cookies for this site.</u>.";
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.FailedToValidateRuntimeKey)
                chartmsg = "<br><u>Failed to validate the runtime license with the server</u>.";
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard && currLicenseType === licensingClasses_1.LicenseType.NoLicense)
                chartmsg = "<br><u>Please use the Licensing wizard to start a trial or activate a serial key.  Click for more information</u>.";
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.DevKeyInRuntimeKey)
                chartmsg = "<br><u>You have set a developer key as a runtime key, which will not work on any other machine.  Click for more information</u>";
            // tslint:disable-next-line: max-line-length
            else if (currLicenseType === licensingClasses_1.LicenseType.Trial_Expired && daysRemaining > 1)
                chartmsg = "<br><u>Please update to the latest version of SciChart. Click for more information</u>.";
            else if (checkStatus === licensingClasses_1.LicenseCheckStatus.NoLicenseInWizard &&
                currLicenseType === licensingClasses_1.LicenseType.Trial_Expired) {
                chartmsg = "<br><u>Please activate a serial key in the Licensing Wizard, or contact sales for an extension.  Click for more information</u>.";
            }
            if (premsg) {
                licenseMessageDiv.style.width = "100%";
                licenseMessageDiv.style.height = "100%";
                licenseMessageDiv.style.top = "0";
                licenseMessageDiv.style.left = "0";
                licenseMessageDiv.style.position = "absolute";
                licenseMessageDiv.style.pointerEvents = "auto";
                licenseMessageDiv.style.cursor = "pointer";
                licenseMessageDiv.style.background = Color_1.EColor.BackgroundColor;
                licenseMessageDiv.style.zIndex = "10";
                licenseMessageDiv.style.display = "block";
                licenseMessageDivChild.style.display = "block";
                licenseMessageDivChild.style.color = "orange";
                licenseMessageDivChild.style.width = "80%";
                licenseMessageDivChild.style.position = "absolute";
                licenseMessageDivChild.style.left = "50%";
                licenseMessageDivChild.style.top = "50%";
                licenseMessageDivChild.style.transform = "translate(-50%, -50%)";
                licenseMessageDivChild.style.textAlign = "center";
                licenseMessageDivChild.style.pointerEvents = "auto";
                if (useLicenseWizard) {
                    licenseMessageDivChild.innerHTML = premsg + chartmsg;
                    createLicenseModal(premsg, postMsg);
                }
                else {
                    licenseMessageDivChild.innerHTML =
                        premsg +
                            "<br><a href=\"https://www.scichart.com/licensing-scichart-js/\"  target=\"_blank\" style=\"color: white\">Click here for licensing information</a>";
                }
                (0, exports.debug)(premsg + "\n" + chartmsg);
            }
        }
        else {
            (0, Telemetry_1.sendTelemetry)();
        }
    }
    updateLicenseMessageDOM(sciChartSurface.domDivContainer, licenseMessageDiv);
};
var cancelChallenge = function () {
    clearTimeout(licenseChallengeTimeout);
    licenseChallengeTimeout = undefined;
    challengeFailCounts = 0;
};
/** @internal Reset module-level license state. For use in unit tests only. */
var resetCheckStatus = function () {
    clearTimeout(licenseChallengeTimeout);
    clearTimeout(wizardTimer);
    licenseChallengeTimeout = undefined;
    challengeFailCounts = 0;
    getLicenseFailCounts = 0;
    checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
    isRuntimeKey = false;
    communityNotice = false;
    runtimeLicenseKey = "";
    licenseManager2dState_1.licenseManager2dState.checkStatus = licensingClasses_1.LicenseCheckStatus.NoLicense;
    licenseManager2dState_1.licenseManager2dState.isDev = false;
};
var clear = function () {
    if (!Globals_1.sciChartDestinations.length && !Globals_1.sciChartSingleDestinations.length && !Globals_1.sciChart3DDestinations.length) {
        clearTimeout(wizardTimer);
        clearTimeout(licenseChallengeTimeout);
        licenseMessageDivChild = null;
        licenseMessageDiv = null;
    }
};
var updateLicenseDisplay = function (sciChartSurface) {
    var licenseInfo = (0, exports.getLicenseInfo)(sciChartSurface.getLicenseContext());
    var is2D = sciChartSurface.surfaceType !== SurfaceType_1.ESurfaceType.SciChart3DSurfaceType;
    // Force the display of the current status
    updateLicenseDisplayInternal(licenseInfo, sciChartSurface, is2D, true);
};
exports.licenseManager = {
    clear: clear,
    cancelChallenge: function () { return cancelChallenge(); },
    /** @internal For unit tests only (no-op unless TEST_ENV=1). */
    resetCheckStatus: function () { if (app_1.IS_TEST_ENV) {
        resetCheckStatus();
    } },
    setRuntimeLicenseKey: function (value) { return (0, exports.setRuntimeLicenseKey)(value); },
    setIsDebugLicensing: function (value) { return (0, exports.setIsDebugLicensing)(value); },
    setLicenseCallback: function (callback) { return (0, exports.setLicenseCallback)(callback); },
    setServerLicenseEndpoint: function (value) { return setServerLicenseEndpoint(value); },
    applyLicense: function (licenseContext, source) { return (0, exports.applyLicense)(licenseContext, source); },
    updateLicenseDisplay: function (sciChartSurface) { return updateLicenseDisplay(sciChartSurface); },
    getLicenseLog: function () { return (0, exports.getLicenseLog)(); },
    clearLogs: function () { return clearLogs(); },
    get logLevel() { return logLevel; },
    set logLevel(value) { logLevel = value; },
    get outputMode() { return outputMode; },
    set outputMode(value) { outputMode = value; },
    get emitLog() { return emitLogFn; },
    set emitLog(fn) { emitLogFn = fn !== null && fn !== void 0 ? fn : defaultEmitLog; },
};
