"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultConfig = void 0;
exports.setLogger = setLogger;
exports.setStatusLogger = setStatusLogger;
exports.setupAndStart = setupAndStart;
var Helpers = __importStar(require("./Helpers"));
var Constants = require("../Declarations/Constants");
var StatusLogger_1 = require("./StatusLogger");
var DiagnosticLogger_1 = require("./DiagnosticLogger");
var Config = require("../Library/Config");
var DataModel_1 = require("./DataModel");
var PrefixHelpers = __importStar(require("../Library/PrefixHelper"));
var Context = require("../Library/Context");
// Private configuration vars
var _appInsights;
exports.defaultConfig = new Config(); // Will read env variables, expose for Agent initialization
var _prefix = "".concat(PrefixHelpers.getResourceProvider()).concat(PrefixHelpers.getOsPrefix()).concat(Constants.AttachTypePrefix.INTEGRATED_AUTO, "_");
var _fullSdkVersion = "".concat(_prefix, "node:").concat(Context.sdkVersion);
var _instrumentationKey = exports.defaultConfig.instrumentationKey;
var _logger = new DiagnosticLogger_1.DiagnosticLogger(console, _instrumentationKey);
var _statusLogger = new StatusLogger_1.StatusLogger(console, _instrumentationKey);
// Env var local constants
var forceStart = process.env.APPLICATIONINSIGHTS_FORCE_START === "true";
/**
 * Sets the attach-time logger
 * @param logger logger which implements the `AgentLogger` interface
 */
function setLogger(logger) {
    return _logger = logger;
}
function setStatusLogger(statusLogger) {
    _statusLogger = statusLogger;
}
/**
 * Try to setup and start this app insights instance if attach is enabled.
 * @param aadTokenCredential Optional AAD credential
 */
function setupAndStart(aadTokenCredential, isAzureFunction) {
    // If app already contains SDK, skip agent attach
    if (!forceStart && Helpers.sdkAlreadyExists(_logger)) {
        _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: false, SDKPresent: true, Reason: "Application Insights SDK already exists." }));
        return null;
    }
    if (!exports.defaultConfig.instrumentationKey) {
        var diagnosticLog = {
            message: "Application Insights wanted to be started, but no Connection String was provided",
            properties: {
                "msgId": DataModel_1.DiagnosticMessageId.missingIkey
            }
        };
        _logger.logError(diagnosticLog);
        _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: false, Reason: diagnosticLog.message }));
        return null;
    }
    try {
        _appInsights = require("../applicationinsights");
        if (_appInsights.defaultClient) {
            // setupAndStart was already called, return the result
            var diagnosticLog_1 = {
                message: "Setup was attempted on the Application Insights Client multiple times. Aborting and returning the first client instance.",
                properties: {
                    "msgId": DataModel_1.DiagnosticMessageId.setupAlreadyCalled
                }
            };
            _logger.logError(diagnosticLog_1);
            return _appInsights;
        }
        /** Sets the SDK version prefix in auto-attach scenarios */
        var prefixInternalSdkVersion = function (envelope, _contextObjects) {
            // If SDK version prefix is not set - set it using {RP}{OS}{Attach Type}_ pattern
            try {
                envelope.tags[appInsightsSDKVersion_1] = _fullSdkVersion;
            }
            catch (e) {
                var diagnosticLog_2 = {
                    message: "Error prefixing SDK version.",
                    exception: e,
                    properties: {
                        "msgId": DataModel_1.DiagnosticMessageId.prefixFailed
                    }
                };
                _logger.logError(diagnosticLog_2);
            }
            return true;
        };
        var copyOverPrefixInternalSdkVersionToHeartBeatMetric = function (envelope, _contextObjects) {
            var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion;
            var sdkVersion = envelope.tags[appInsightsSDKVersion] || "";
            if (envelope.name === Constants.HeartBeatMetricName) {
                (envelope.data.baseData).properties = (envelope.data.baseData).properties || {};
                (envelope.data.baseData).properties["sdk"] = sdkVersion;
            }
            return true;
        };
        // Instrument the SDK
        Context.sdkPrefix = _prefix;
        _appInsights.setup();
        var appInsightsSDKVersion_1 = _appInsights.defaultClient.context.keys.internalSdkVersion;
        // Azure Functions
        if (isAzureFunction) {
            // Agent will always run in parallel with Azure Functions .NET Agent, disable requests and exceptions to avoid duplication of telemetry
            // Check if config is not already setup by JSON or env variables
            if (_appInsights.defaultClient.config.enableSendLiveMetrics === undefined) {
                _appInsights.defaultClient.config.enableSendLiveMetrics = false;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectPerformance === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectPerformance = false;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectPreAggregatedMetrics === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectPreAggregatedMetrics = false;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions = false;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectRequests === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectRequests = false;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectDependencies === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectDependencies = true;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectHeartbeat === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectHeartbeat = true;
            }
            if (_appInsights.defaultClient.config.enableUseDiskRetryCaching === undefined) {
                _appInsights.defaultClient.config.enableUseDiskRetryCaching = true;
            }
        }
        // App Services
        else {
            // Check if config is not already setup by JSON or env variables
            if (_appInsights.defaultClient.config.enableSendLiveMetrics === undefined) {
                _appInsights.defaultClient.config.enableSendLiveMetrics = true;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectPerformance === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectPerformance = true;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectPreAggregatedMetrics === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectPreAggregatedMetrics = true;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectIncomingRequestAzureFunctions = false;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectRequests === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectRequests = true;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectDependencies === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectDependencies = true;
            }
            if (_appInsights.defaultClient.config.enableAutoCollectHeartbeat === undefined) {
                _appInsights.defaultClient.config.enableAutoCollectHeartbeat = true;
            }
            if (_appInsights.defaultClient.config.enableUseDiskRetryCaching === undefined) {
                _appInsights.defaultClient.config.enableUseDiskRetryCaching = true;
            }
        }
        _appInsights.defaultClient.addTelemetryProcessor(prefixInternalSdkVersion);
        _appInsights.defaultClient.addTelemetryProcessor(copyOverPrefixInternalSdkVersionToHeartBeatMetric);
        if (aadTokenCredential) {
            var diagnosticLog_3 = {
                message: "Application Insights using AAD Token Credential.",
                properties: {
                    "msgId": DataModel_1.DiagnosticMessageId.aadEnabled
                }
            };
            _logger.logMessage(diagnosticLog_3);
            _appInsights.defaultClient.config.aadTokenCredential = aadTokenCredential;
        }
        _appInsights.start();
        // Set the SDK verison in the context
        _appInsights.defaultClient.context.tags[appInsightsSDKVersion_1] = _fullSdkVersion;
        // Add attach flag in Statsbeat
        var statsbeat = _appInsights.defaultClient.getStatsbeat();
        if (statsbeat) {
            statsbeat.setCodelessAttach();
        }
        // Agent successfully instrumented the SDK
        var diagnosticLog = {
            message: "Application Insights was started succesfully.",
            properties: {
                "msgId": DataModel_1.DiagnosticMessageId.attachSuccessful
            }
        };
        _logger.logMessage(diagnosticLog);
        _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: true }));
    }
    catch (e) {
        var diagnosticLog = {
            message: "Error setting up Application Insights.",
            exception: e,
            properties: {
                "msgId": DataModel_1.DiagnosticMessageId.unknownError
            }
        };
        _logger.logError(diagnosticLog);
        _statusLogger.logStatus(__assign(__assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS), { AgentInitializedSuccessfully: false, Reason: "Error setting up Application Insights: ".concat(e && e.message) }));
    }
    return _appInsights;
}
//# sourceMappingURL=Default.js.map