/*
 * Application Insights JavaScript SDK - Core, 3.3.10
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */


import { objDefine } from "@nevware21/ts-utils";
import { normalizeJsName } from "./HelperFuncs";
import { STR_EMPTY } from "./InternalConstants";
import { newId } from "./RandomHelper";
var version = '3.3.10';
var instanceName = "." + newId(6);
var _dataUid = 0;
// Accepts only:
//  - Node
//    - Node.ELEMENT_NODE
//    - Node.DOCUMENT_NODE
//  - Object
//    - Any
function _canAcceptData(target) {
    return target.nodeType === 1 || target.nodeType === 9 || !(+target.nodeType);
}
function _getCache(data, target) {
    var theCache = target[data.id];
    if (!theCache) {
        theCache = {};
        try {
            if (_canAcceptData(target)) {
                objDefine(target, data.id, {
                    e: false,
                    v: theCache
                });
            }
        }
        catch (e) {
            // Not all environments allow extending all objects, so just ignore the cache in those cases
        }
    }
    return theCache;
}
export function createUniqueNamespace(name, includeVersion) {
    if (includeVersion === void 0) { includeVersion = false; }
    return normalizeJsName(name + (_dataUid++) + (includeVersion ? "." + version : STR_EMPTY) + instanceName);
}
export function createElmNodeData(name) {
    var data = {
        id: createUniqueNamespace("_aiData-" + (name || STR_EMPTY) + "." + version),
        accept: function (target) {
            return _canAcceptData(target);
        },
        get: function (target, name, defValue, addDefault) {
            var theCache = target[data.id];
            if (!theCache) {
                if (addDefault) {
                    // Side effect is adds the cache
                    theCache = _getCache(data, target);
                    theCache[normalizeJsName(name)] = defValue;
                }
                return defValue;
            }
            return theCache[normalizeJsName(name)];
        },
        kill: function (target, name) {
            if (target && target[name]) {
                try {
                    delete target[name];
                }
                catch (e) {
                    // Just cleaning up, so if this fails -- ignore
                }
            }
        }
    };
    return data;
}
//# sourceMappingURL=DataCacheHelper.js.map