"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const timeUtils = require("../../Utilities/timeUtils");
const internal_1 = require("../../internal");
const TelemetryConfig_1 = require("../../Utilities/Logging/TelemetryConfig");
const TelemetryKustoClient_1 = require("../../Utilities/Logging/TelemetryKustoClient");
const testHelper_1 = require("../testHelper");
describe('Utilities.TelemetryKustoClient', () => {
    /** Environment variables for Kusto configuration. */
    const tenantId = process.env['KUSTO_TENANTID'];
    const clientId = process.env['KUSTO_CLIENTID'];
    const secret = process.env['KUSTO_SECRET'];
    const clusterName = process.env['KUSTO_CLUSTER'];
    const databaseName = process.env['KUSTO_DATABASE'];
    const infoTable = process.env["KUSTO_INFOTABLE"];
    const warningTable = process.env["KUSTO_WARNINGTABLE"];
    const errorTable = process.env["KUSTO_ERRORTABLE"];
    /** The path between TestDataPath and TestName. */
    const testsSubpath = 'Utilities';
    /** Declare a blackhole callback. */
    const eventCallback = () => { };
    const kustoIt = process.env['KUSTO_RUNTESTS'] === '1' ? it : it.skip;
    kustoIt('TestInitializeClientWithDefaultDatabase', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = initializeClientWithDefaultDatabase();
        corpus.telemetryClient.enable();
        yield callResolveManifestWithAnEntity(corpus);
        if (!corpus.telemetryClient.checkRequestQueueIsEmpty()) {
            yield corpus.telemetryClient.ingestRequestQueue();
        }
    }));
    kustoIt('TestInitializeClientWithUserDatabase', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = initializeClientWithUserDatabase();
        corpus.telemetryClient.enable();
        yield callResolveManifestWithAnEntity(corpus);
        if (!corpus.telemetryClient.checkRequestQueueIsEmpty()) {
            yield corpus.telemetryClient.ingestRequestQueue();
        }
    }));
    kustoIt('TestAadAppAuthorizationException', () => __awaiter(void 0, void 0, void 0, function* () {
        // initialize with some dummy credentials
        const corpus = new internal_1.CdmCorpusDefinition();
        const kustoConfig = new TelemetryConfig_1.TelemetryConfig(internal_1.environmentType.DEV, 'West US', false, 'tenantId', 'clientId', 'secret', 'clusterName', 'databaseName', internal_1.azureCloudEndpoint.AzurePublic);
        corpus.telemetryClient = new TelemetryKustoClient_1.TelemetryKustoClient(corpus.ctx, kustoConfig);
        try {
            yield kustoConfig.getAuthenticationToken();
        }
        catch (err) {
            expect(`${err}`.includes('There was an error while acquiring Kusto authorization Token with client ID/secret authentication')).toBeTruthy();
        }
    }));
    kustoIt('TestMaximumTimeoutAndRetries', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = initializeClientWithDefaultDatabase();
        // set timeout to 1 millisecond so the function will reach max timeout and fail
        corpus.telemetryClient.timeoutMilliseconds = 1;
        const query = `.ingest inline into table infoLogs<|\n${timeUtils.getFormattedDateString(new Date())},class name,method name,some message,None,corpus path,correlation id,api correlation id,app id,property`;
        try {
            yield corpus.telemetryClient.postKustoQuery(query);
        }
        catch (err) {
            expect(err).toBe('The number of retries has exceeded the maximum number allowed by the client.');
        }
    }));
    function initializeClientWithDefaultDatabase() {
        const corpus = testHelper_1.testHelper.getLocalCorpus(testsSubpath, 'TestTelemetryKustoClient');
        expect(internal_1.StringUtils.isNullOrWhiteSpace(tenantId)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(clientId)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(secret)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(clusterName)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(databaseName)).toBe(false);
        const kustoConfig = new TelemetryConfig_1.TelemetryConfig(internal_1.environmentType.DEV, 'West US', false, tenantId, clientId, secret, clusterName, databaseName, internal_1.azureCloudEndpoint.AzurePublic);
        corpus.telemetryClient = new TelemetryKustoClient_1.TelemetryKustoClient(corpus.ctx, kustoConfig);
        corpus.appId = 'CDM Integration Test';
        // set callback to receive error, warning and progress logs.
        corpus.setEventCallback(eventCallback, internal_1.cdmStatusLevel.progress);
        return corpus;
    }
    function initializeClientWithUserDatabase() {
        const corpus = testHelper_1.testHelper.getLocalCorpus(testsSubpath, 'TestTelemetryKustoClient');
        // TODO: need to investigate why only Java not failing if using event callback from GetLocalCorpus() 
        // set callback to receive error, warning and progress logs.
        corpus.setEventCallback(eventCallback, internal_1.cdmStatusLevel.progress);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(tenantId)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(clientId)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(secret)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(clusterName)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(databaseName)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(infoTable)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(warningTable)).toBe(false);
        expect(internal_1.StringUtils.isNullOrWhiteSpace(errorTable)).toBe(false);
        const kustoConfig = new TelemetryConfig_1.TelemetryConfig(internal_1.environmentType.DEV, 'West US', false, tenantId, clientId, secret, clusterName, databaseName, internal_1.azureCloudEndpoint.AzurePublic, infoTable, warningTable, errorTable);
        corpus.telemetryClient = new TelemetryKustoClient_1.TelemetryKustoClient(corpus.ctx, kustoConfig);
        return corpus;
    }
    function callResolveManifestWithAnEntity(corpus) {
        return __awaiter(this, void 0, void 0, function* () {
            let manifest = corpus.MakeObject(internal_1.cdmObjectType.manifestDef, 'dummy');
            corpus.storage.fetchRootFolder('local').documents.push(manifest, "default.manifest.cdm.json");
            let entity1 = corpus.MakeObject(internal_1.cdmObjectType.entityDef, 'MyEntity');
            let someAttrib1 = corpus.MakeObject(internal_1.cdmObjectType.typeAttributeDef, 'MyAttribute', false);
            someAttrib1.dataType = corpus.MakeRef(internal_1.cdmObjectType.dataTypeRef, 'entityId', true);
            entity1.attributes.push(someAttrib1);
            let entity1Doc = corpus.MakeObject(internal_1.cdmObjectType.documentDef, 'MyEntity.cdm.json');
            entity1Doc.definitions.push(entity1);
            corpus.storage.fetchRootFolder('local').documents.push(entity1Doc);
            manifest.entities.push(entity1);
            yield manifest.createResolvedManifestAsync('new dummy', null);
        });
    }
});
//# sourceMappingURL=TelemetryKustoClient.test.js.map