/*
 * Application Insights JavaScript SDK - Debug Plugin, 3.4.0-nightlybeta3.2602-27
 * Copyright (c) Microsoft and contributors. All rights reserved.
 */


import { __extendsFn as __extends } from "@microsoft/applicationinsights-shims";
import dynamicProto from "@microsoft/dynamicproto-js";
import { BaseTelemetryPlugin, InstrumentFunc, arrForEach, arrIndexOf, dateNow, getDebugExt, isArray, isFunction, isUndefined, objForEachKey } from "@microsoft/applicationinsights-core-js";
import { _DYN_APPEND_CHILD, _DYN_CLASS_NAME, _DYN_CREATE_ELEMENT, _DYN_DISABLE_NOTIFICATION0, _DYN_DUMP_TO_CONSOLE, _DYN_EXCLUDE_KEYS, _DYN_IDENTIFIER, _DYN_IS_DISPLAYED, _DYN_LENGTH, _DYN_LOG_PROCESS_TELEMETR1, _DYN_NAME, _DYN_NEW_LOG_ENTRY, _DYN_PUSH, _DYN_SHOW_CHILDREN, _DYN_STOP_PROPAGATION } from "./__DynamicConstants";
import { Dashboard } from "./components/Dashboard";
import { DebugBin, DebugBinParent } from "./components/debugBins";
import { getTargetName } from "./components/helpers";
import { permStyle } from "./components/styleNodeSrc";
var getDefaultConfig = function () {
    var config = {
        trackers: function () { return [
            "flush",
            "track",
            "trackEvent",
            "trackPageView",
            "trackPageViewPerformance",
            "trackException",
            "trackTrace",
            "trackMetric",
            "trackDependencyData",
            "processTelemetry",
            "throwInternal",
            "logInternalMessage",
            "triggerSend",
            "_sender",
            "perfEvent",
            "initialize"
        ]; },
        excludeKeys: function () { return [
            "_dynInstFuncs",
            "_getTelCtx",
            "_baseTelInit",
            "diagLog",
            "isInitialized",
            "setInitialized",
            "setNextPlugin",
            "processNext"
        ]; },
        cssPrefix: function () { return "ai"; },
        disableNotifications: function () { return false; },
        dumpToConsole: function () { return false; },
        maxMessages: function () { return 5000; },
        showFunctions: function () { return false; },
        logProcessTelemetry: function () { return false; }
    };
    return config;
};
var DebugPlugin = /** @class */ (function (_super) {
    __extends(DebugPlugin, _super);
    function DebugPlugin() {
        var _this = _super.call(this) || this;
        _this.identifier = DebugPlugin[_DYN_IDENTIFIER /* @min:%2eidentifier */];
        var dashboard;
        /**
         * the style that will be permanently embedded in the webpage
         * TODO: manage style conflicts (prepend unique ID to relevant class names?)
         */
        var permStyleEl;
        /**
         * an object containing the individual debug bin items
         */
        var debugBins;
        /**
         * the parent containing all the individual debugBins
         */
        var debugBinParent;
        /**
         * the different telemetry functions that will be tracked
         */
        var trackers;
        /**
         * timestamp used to track number of seconds since webpage was loaded
         */
        var startTime = +new Date();
        /**
         * the config for this plugin
         */
        var _theConfig = getDefaultConfig();
        dynamicProto(DebugPlugin, _this, function (_self, base) {
            _self.initialize = function (config, core, extensions, pluginChain) {
                if (!_self.isInitialized()) {
                    base.initialize(config, core, extensions, pluginChain);
                    var defaultConfig = getDefaultConfig();
                    var ctx_1 = _self._getTelCtx();
                    var identifier_1 = _self[_DYN_IDENTIFIER /* @min:%2eidentifier */];
                    objForEachKey(defaultConfig, function (field, value) {
                        _theConfig[field] = function () { return ctx_1.getConfig(identifier_1, field, value()); };
                    });
                    var foundTrackers_1 = [];
                    trackers = _theConfig.trackers();
                    var prefix = _theConfig.cssPrefix();
                    // 1. Listen to Notifications
                    if (!_theConfig[_DYN_DISABLE_NOTIFICATION0 /* @min:%2edisableNotifications */]()) {
                        var notifyMgr = (isFunction(core.getNotifyMgr) && core.getNotifyMgr()) || core["_notificationManager"];
                        if (notifyMgr) {
                            notifyMgr.addNotificationListener({
                                eventsSent: function (events) {
                                    dashboard[_DYN_NEW_LOG_ENTRY /* @min:%2enewLogEntry */](events, dateNow() - startTime, "Notification:eventsSent", 0, "eventsSent");
                                },
                                eventsDiscarded: function (events, reason) {
                                    dashboard[_DYN_NEW_LOG_ENTRY /* @min:%2enewLogEntry */]({
                                        events: events,
                                        reason: reason
                                    }, dateNow() - startTime, "Notification:eventsDiscarded", 0, "eventsDiscarded");
                                },
                                eventsSendRequest: function (sendReason, isAsync) {
                                    dashboard[_DYN_NEW_LOG_ENTRY /* @min:%2enewLogEntry */]({
                                        sendReason: sendReason,
                                        isAsync: isAsync
                                    }, dateNow() - startTime, "Notification:eventsSendRequest", 0, "eventsSendRequest");
                                },
                                perfEvent: function (perfEvent) {
                                    var evtName = "Notification:perfEvent[".concat(perfEvent.name, "]");
                                    dashboard[_DYN_NEW_LOG_ENTRY /* @min:%2enewLogEntry */](perfEvent, dateNow() - startTime, evtName, 0, "perfEvent");
                                }
                            });
                            if (arrIndexOf(trackers, "eventsSent") !== -1) {
                                foundTrackers_1[_DYN_PUSH /* @min:%2epush */]("eventsSent");
                            }
                            if (arrIndexOf(trackers, "eventsSendRequest") !== -1) {
                                foundTrackers_1[_DYN_PUSH /* @min:%2epush */]("eventsSendRequest");
                            }
                            if (arrIndexOf(trackers, "eventsDiscarded") !== -1) {
                                foundTrackers_1[_DYN_PUSH /* @min:%2epush */]("eventsDiscarded");
                            }
                            if (arrIndexOf(trackers, "perfEvent") !== -1) {
                                foundTrackers_1[_DYN_PUSH /* @min:%2epush */]("perfEvent");
                            }
                        }
                    }
                    // 2. Get all of the extensions and channels
                    debugBins = {};
                    var targetObjects_1 = [core, _self.diagLog()];
                    // Get all of the config extensions
                    if (config.extensions) {
                        arrForEach(config.extensions, function (ext) {
                            _addTargets(targetObjects_1, ext);
                        });
                    }
                    // Get all of the passed extensions
                    if (extensions) {
                        arrForEach(extensions, function (ext) {
                            _addTargets(targetObjects_1, ext);
                        });
                    }
                    if (isFunction(core["getTransmissionControls"])) {
                        var channelControls = core["getTransmissionControls"]();
                        if (channelControls) {
                            arrForEach(channelControls, function (channel) {
                                if (isArray(channel)) {
                                    arrForEach(channel, function (theChannel) {
                                        _addTargets(targetObjects_1, theChannel);
                                    });
                                }
                            });
                        }
                    }
                    if (isFunction(core["getChannels"])) {
                        var channelControls = core["getChannels"]();
                        if (channelControls) {
                            arrForEach(channelControls, function (theChannel) {
                                _addTargets(targetObjects_1, theChannel);
                            });
                        }
                    }
                    // 3. Instrument the functions
                    arrForEach(trackers, function (tracker) {
                        arrForEach(targetObjects_1, function (target, idx) {
                            var val = InstrumentFunc(target, tracker, {
                                req: _handleInstPreHook(),
                                rsp: _handleInstPostHook()
                            }, true);
                            if (val) {
                                if (arrIndexOf(foundTrackers_1, tracker) === -1) {
                                    foundTrackers_1[_DYN_PUSH /* @min:%2epush */](tracker);
                                }
                            }
                        });
                    });
                    // Sort the items
                    foundTrackers_1 = foundTrackers_1.sort();
                    // 4. Create the Dashboard
                    dashboard = new Dashboard({
                        prefix: prefix,
                        trackers: foundTrackers_1,
                        excludeKeys: _theConfig[_DYN_EXCLUDE_KEYS /* @min:%2eexcludeKeys */](),
                        maxMessages: _theConfig.maxMessages(),
                        includeFunctions: _theConfig.showFunctions()
                    });
                    // 5. setup debugBin
                    var debugBinContainer = document[_DYN_CREATE_ELEMENT /* @min:%2ecreateElement */]("div");
                    debugBinContainer[_DYN_CLASS_NAME /* @min:%2eclassName */] = "".concat(prefix, "-debug-bin-container");
                    debugBinParent = new DebugBinParent(debugBinContainer, [], 0, prefix);
                    arrForEach(foundTrackers_1, function (tracker, idx) {
                        debugBins[tracker] = new DebugBin(tracker, 0, debugBinParent, (idx + 1) * 50);
                    });
                    // 6. append permanent style
                    permStyleEl = document[_DYN_CREATE_ELEMENT /* @min:%2ecreateElement */]("style");
                    permStyleEl.innerHTML = permStyle(prefix);
                    document.head[_DYN_APPEND_CHILD /* @min:%2eappendChild */](permStyleEl);
                    // 7. add button to debugBinParent
                    debugBinParent.addButton(function (evt) {
                        evt[_DYN_STOP_PROPAGATION /* @min:%2estopPropagation */]();
                        if (dashboard[_DYN_IS_DISPLAYED /* @min:%2eisDisplayed */]()) {
                            dashboard.hide();
                        }
                        else {
                            dashboard.show();
                        }
                    }, "show dashboard");
                    document.body[_DYN_APPEND_CHILD /* @min:%2eappendChild */](debugBinContainer);
                    // 8. Log the config as "keep" so it won't be dropped or cleared
                    dashboard[_DYN_NEW_LOG_ENTRY /* @min:%2enewLogEntry */](config, 0, "config", 0, "config", true);
                }
            };
            function _addTarget(targetObjects, ext) {
                if (ext && arrIndexOf(targetObjects, ext) === -1) {
                    targetObjects[_DYN_PUSH /* @min:%2epush */](ext);
                    return true;
                }
                return false;
            }
            function _addTargets(targetObjects, ext) {
                if (_addTarget(targetObjects, ext)) {
                    if (isFunction(ext["_getDbgPlgTargets"])) {
                        var extra = ext["_getDbgPlgTargets"]();
                        if (isArray(extra)) {
                            arrForEach(extra, function (tgt) {
                                _addTargets(targetObjects, tgt);
                            });
                        }
                    }
                }
            }
            function _createInstrumentObject(funcArgs, orgArgs) {
                var result = {
                    funcName: funcArgs[_DYN_NAME /* @min:%2ename */],
                    inst: funcArgs.inst
                };
                if (orgArgs && orgArgs[_DYN_LENGTH /* @min:%2elength */]) {
                    result.args = orgArgs;
                }
                if (!isUndefined(funcArgs.err)) {
                    result.err = funcArgs.err;
                }
                if (!isUndefined(funcArgs.rslt)) {
                    result.rslt = funcArgs.rslt;
                }
                return result;
            }
            function _getEvtPrefix(funcArgs) {
                var identifier = getTargetName(funcArgs.inst);
                var evtPrefix = funcArgs[_DYN_NAME /* @min:%2ename */];
                if (identifier) {
                    evtPrefix += ":" + identifier;
                }
                return evtPrefix;
            }
            function _logEntry(theEvent, evtName, kind) {
                dashboard[_DYN_NEW_LOG_ENTRY /* @min:%2enewLogEntry */](theEvent, dateNow() - startTime, evtName, 0, kind);
                var dbgExt = getDebugExt(_self.core.config);
                if (dbgExt && dbgExt.debugMsg) {
                    dbgExt.debugMsg(evtName, theEvent);
                }
            }
            function _handleInstPreHook() {
                return function (funcArgs) {
                    var orgArgs = [];
                    for (var _i = 1; _i < arguments.length; _i++) {
                        orgArgs[_i - 1] = arguments[_i];
                    }
                    (debugBins[funcArgs.name] || debugBins.default).increment();
                    if (funcArgs[_DYN_NAME /* @min:%2ename */] === "trackException" && !debugBinParent[_DYN_SHOW_CHILDREN /* @min:%2eshowChildren */]) {
                        debugBinParent.addClassToEl("notify");
                    }
                    var evtPrefix = _getEvtPrefix(funcArgs);
                    _logEntry(_createInstrumentObject(funcArgs, orgArgs), evtPrefix, funcArgs[_DYN_NAME /* @min:%2ename */]);
                    if (_theConfig[_DYN_DUMP_TO_CONSOLE /* @min:%2edumpToConsole */]() && console && console.log) {
                        console.log("[".concat(evtPrefix, "] preProcess - funcArgs: "), funcArgs);
                        console.log("[".concat(evtPrefix, "] preProcess - orgArgs: "), orgArgs);
                    }
                };
            }
            function _handleInstPostHook() {
                return function (funcArgs) {
                    var orgArgs = [];
                    for (var _i = 1; _i < arguments.length; _i++) {
                        orgArgs[_i - 1] = arguments[_i];
                    }
                    if (!isUndefined(funcArgs.err)) {
                        var evtPrefix = _getEvtPrefix(funcArgs);
                        if (!debugBinParent[_DYN_SHOW_CHILDREN /* @min:%2eshowChildren */]) {
                            debugBinParent.addClassToEl("notify");
                        }
                        // The called function threw an exception
                        _logEntry(_createInstrumentObject(funcArgs, orgArgs), evtPrefix, funcArgs[_DYN_NAME /* @min:%2ename */]);
                        if (_theConfig[_DYN_DUMP_TO_CONSOLE /* @min:%2edumpToConsole */]() && console && console.log) {
                            console.log("[".concat(evtPrefix, "] complete"));
                        }
                    }
                };
            }
            _self.processTelemetry = function (event, itemCtx) {
                if (_theConfig[_DYN_DUMP_TO_CONSOLE /* @min:%2edumpToConsole */]() && console && console.log) {
                    console.log("[".concat(_self.identifier, ":processTelemetry] complete"));
                }
                if (!debugBins["processTelemetry"] && _theConfig[_DYN_LOG_PROCESS_TELEMETR1 /* @min:%2elogProcessTelemetry */]() === true) {
                    _logEntry(event, "[".concat(_self.identifier, ":processTelemetry[").concat(event.baseType, "]"), "processTelemetry");
                }
                _self.processNext(event, itemCtx);
            };
        });
        return _this;
    }
// Removed Stub for DebugPlugin.prototype.initialize.
// Removed Stub for DebugPlugin.prototype.processTelemetry.
    DebugPlugin.identifier = "DebugPlugin";
    return DebugPlugin;
}(BaseTelemetryPlugin));
export default DebugPlugin;
//# sourceMappingURL=DebugPlugin.js.map