/*
 * Application Insights JavaScript SDK - Properties Plugin, 3.4.3
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */


import dynamicProto from "@microsoft/dynamicproto-js";
import { _throwInternal, newId, onConfigChange, safeGetCookieMgr, safeGetLogger, toISOString, utlRemoveStorage } from "@microsoft/applicationinsights-core-js";
import { objDefine } from "@nevware21/ts-utils";
import { _DYN_ACCOUNT_ID, _DYN_AUTHENTICATED_ID, _DYN_AUTH_USER_COOKIE_NAM7, _DYN_COOKIE_SEPARATOR, _DYN_IS_NEW_USER, _DYN_IS_USER_COOKIE_SET } from "../__DynamicConstants";
function _validateUserInput(id) {
    // Validate:
    // 1. Id is a non-empty string.
    // 2. It does not contain special characters for cookies.
    if (typeof id !== "string" ||
        !id ||
        id.match(/,|;|=| |\|/)) {
        return false;
    }
    return true;
}
var User = /** @class */ (function () {
    function User(config, core, unloadHookContainer) {
        /**
         * A flag indicating whether this represents a new user
         */
        this.isNewUser = false;
        /**
         * A flag indicating whether the user cookie has been set
         */
        this.isUserCookieSet = false;
        var _logger = safeGetLogger(core);
        var _cookieManager = safeGetCookieMgr(core);
        var _storageNamePrefix;
        dynamicProto(User, this, function (_self) {
            // Define _self.config
            objDefine(_self, "config", {
                g: function () { return config; }
            });
            var unloadHook = onConfigChange(config, function () {
                var userCookiePostfix = config.userCookiePostfix || "";
                _storageNamePrefix = User.userCookieName + userCookiePostfix;
                // get userId or create new one if none exists
                var cookie = _cookieManager.get(_storageNamePrefix);
                if (cookie) {
                    _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = false;
                    var params = cookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);
                    if (params.length > 0) {
                        _self.id = params[0];
                        // we already have a cookie
                        _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = !!_self.id;
                    }
                }
                if (!_self.id) {
                    _self.id = _generateNewId();
                    var newCookie = _generateNewCookie(_self.id);
                    _setUserCookie(newCookie.join(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));
                    // If we have an config.namePrefix() + ai_session in local storage this means the user actively removed our cookies.
                    // We should respect their wishes and clear ourselves from local storage
                    var name_1 = (config.namePrefix || "") + "ai_session";
                    utlRemoveStorage(_logger, name_1);
                }
                // We still take the account id from the ctor param for backward compatibility.
                // But if the the customer set the accountId through the newer setAuthenticatedUserContext API, we will override it.
                _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = config[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] || undefined;
                // Get the auth user id and account id from the cookie if exists
                // Cookie is in the pattern: <authenticatedId>|<accountId>
                var authCookie = _cookieManager.get(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */]);
                if (authCookie) {
                    authCookie = decodeURI(authCookie);
                    var authCookieString = authCookie.split(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);
                    if (authCookieString[0]) {
                        _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authCookieString[0];
                    }
                    if (authCookieString.length > 1 && authCookieString[1]) {
                        _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = authCookieString[1];
                    }
                }
            });
            unloadHookContainer && unloadHookContainer.add(unloadHook);
            function _generateNewId() {
                var theConfig = (config || {});
                var getNewId = theConfig.getNewId || newId;
                var id = getNewId(theConfig.idLength ? config.idLength : 22);
                return id;
            }
            function _generateNewCookie(userId) {
                var acqStr = toISOString(new Date());
                _self.accountAcquisitionDate = acqStr;
                _self[_DYN_IS_NEW_USER /* @min:%2eisNewUser */] = true;
                var newCookie = [userId, acqStr];
                return newCookie;
            }
            function _setUserCookie(cookie) {
                // without expiration, cookies expire at the end of the session
                // set it to 365 days from now
                // 365 * 24 * 60 * 60 = 31536000
                var oneYear = 31536000;
                _self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */] = _cookieManager.set(_storageNamePrefix, cookie, oneYear);
            }
            _self.setAuthenticatedUserContext = function (authenticatedUserId, accountId, storeInCookie) {
                if (storeInCookie === void 0) { storeInCookie = false; }
                // Validate inputs to ensure no cookie control characters.
                var isInvalidInput = !_validateUserInput(authenticatedUserId) || (accountId && !_validateUserInput(accountId));
                if (isInvalidInput) {
                    _throwInternal(_logger, 2 /* eLoggingSeverity.WARNING */, 60 /* _eInternalMessageId.SetAuthContextFailedAccountName */, "Setting auth user context failed. " +
                        "User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.", true);
                    return;
                }
                // Create cookie string.
                _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = authenticatedUserId;
                var authCookie = _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */];
                if (accountId) {
                    _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = accountId;
                    authCookie = [_self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */], _self.accountId].join(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]);
                }
                if (storeInCookie) {
                    // Set the cookie. No expiration date because this is a session cookie (expires when browser closed).
                    // Encoding the cookie to handle unexpected unicode characters.
                    _cookieManager.set(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */], encodeURI(authCookie));
                }
            };
            /**
             * Clears the authenticated user id and the account id from the user context.
             * @returns {}
             */
            _self.clearAuthenticatedUserContext = function () {
                _self[_DYN_AUTHENTICATED_ID /* @min:%2eauthenticatedId */] = null;
                _self[_DYN_ACCOUNT_ID /* @min:%2eaccountId */] = null;
                _cookieManager.del(User[_DYN_AUTH_USER_COOKIE_NAM7 /* @min:%2eauthUserCookieName */]);
            };
            _self.update = function (userId) {
                // Optimizations to avoid setting and processing the cookie when not needed
                if (_self.id !== userId || !_self[_DYN_IS_USER_COOKIE_SET /* @min:%2eisUserCookieSet */]) {
                    var user_id = userId ? userId : _generateNewId();
                    var user_cookie = _generateNewCookie(user_id);
                    _setUserCookie(user_cookie.join(User[_DYN_COOKIE_SEPARATOR /* @min:%2ecookieSeparator */]));
                }
            };
        });
    }
// Removed Stub for User.prototype.setAuthenticatedUserContext.
// Removed Stub for User.prototype.clearAuthenticatedUserContext.
// Removed Stub for User.prototype.update.
    User.cookieSeparator = "|";
    User.userCookieName = "ai_user";
    User.authUserCookieName = "ai_authUser";
    return User;
}());
export { User };
//# sourceMappingURL=User.js.map