"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 using_statement_1 = require("using-statement");
const CdmCollectionHelperFunctions_1 = require("../../../Cdm/CdmCollection/CdmCollectionHelperFunctions");
const internal_1 = require("../../../../internal");
const Persistence_1 = require("../../../../Persistence");
const testHelper_1 = require("../../../testHelper");
describe('Persistence.CdmFolder.DataPartitionPattern', () => {
    /// <summary>
    /// The path between TestDataPath and TestName.
    /// </summary>
    const testsSubpath = 'Persistence/CdmFolder/DataPartitionPattern';
    /**
     * Testing for folder with local entity declaration with data partition patterns.
     */
    it('TestLoadLocalEntityWithDataPartitionPattern', () => {
        const readFile = testHelper_1.testHelper.getInputFileContent(testsSubpath, 'TestLoadLocalEntityWithDataPartitionPattern', 'entities.manifest.cdm.json');
        const cdmManifest = Persistence_1.CdmFolder.ManifestPersistence.fromObject(new internal_1.resolveContext(new internal_1.CdmCorpusDefinition(), undefined), '', '', '', JSON.parse(readFile));
        expect(cdmManifest.entities.length)
            .toBe(2);
        const entity1 = cdmManifest.entities.allItems[0];
        expect(entity1.getObjectType())
            .toBe(internal_1.cdmObjectType.localEntityDeclarationDef);
        expect(entity1.dataPartitionPatterns.length)
            .toBe(1);
        const pattern1 = entity1.dataPartitionPatterns.allItems[0];
        expect(pattern1.name)
            .toBe('testPattern');
        expect(pattern1.explanation)
            .toBe('test explanation');
        expect(pattern1.rootLocation)
            .toBe('test location');
        expect(pattern1.regularExpression)
            .toBe('\\s*');
        expect(pattern1.parameters.length)
            .toBe(2);
        expect(pattern1.parameters[0])
            .toBe('testParam1');
        expect(pattern1.parameters[1])
            .toBe('testParam2');
        expect(pattern1.specializedSchema)
            .toBe('test special schema');
        expect(pattern1.exhibitsTraits.length)
            .toBe(1);
        const entity2 = cdmManifest.entities.allItems[1];
        expect(entity2.getObjectType())
            .toBe(internal_1.cdmObjectType.localEntityDeclarationDef);
        expect(entity2.dataPartitionPatterns.length)
            .toBe(1);
        const pattern2 = entity2.dataPartitionPatterns.allItems[0];
        expect(pattern2.name)
            .toBe('testPattern2');
        expect(pattern2.rootLocation)
            .toBe('test location2');
        expect(pattern2.globPattern)
            .toBe('/*.csv');
        const manifestData = Persistence_1.CdmFolder.ManifestPersistence.toData(cdmManifest, new internal_1.resolveOptions(), new internal_1.copyOptions());
        expect(manifestData.entities.length)
            .toBe(2);
        const entityData1 = manifestData.entities[0];
        expect(entityData1.dataPartitionPatterns.length)
            .toBe(1);
        const patternData1 = entityData1.dataPartitionPatterns[0];
        expect(patternData1.name)
            .toBe('testPattern');
        expect(patternData1.explanation)
            .toBe('test explanation');
        expect(patternData1.rootLocation)
            .toBe('test location');
        expect(patternData1.regularExpression)
            .toBe('\\s*');
        expect(patternData1.parameters.length)
            .toBe(2);
        expect(patternData1.parameters[0])
            .toBe('testParam1');
        expect(patternData1.parameters[1])
            .toBe('testParam2');
        expect(patternData1.specializedSchema)
            .toBe('test special schema');
        expect(patternData1.exhibitsTraits.length)
            .toBe(1);
        const entityData2 = manifestData.entities[1];
        expect(entityData2.dataPartitionPatterns.length)
            .toBe(1);
        const patternData2 = entityData2.dataPartitionPatterns[0];
        expect(patternData2.name)
            .toBe('testPattern2');
        expect(patternData2.rootLocation)
            .toBe('test location2');
        expect(patternData2.globPattern)
            .toBe('/*.csv');
    });
    /**
     * Testing loading manifest with local entity declaration having an incremental partition pattern without incremental trait.
     */
    it('TestFromIncrementalPartitionPatternWithoutTrait', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = testHelper_1.testHelper.getLocalCorpus(testsSubpath, 'TestFromIncrementalPartitionPatternWithoutTrait');
        let errorMessageVerified = false;
        // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition)
        corpus.setEventCallback((level, message) => {
            if (message.indexOf('Failed to persist object \'DeletePattern\'. This object does not contain the trait \'is.partition.incremental\', so it should not be in the collection \'incrementalPartitionPatterns\'. | fromData') !== -1) {
                errorMessageVerified = true;
            }
            else {
                throw new Error('Some unexpected failure - ' + message);
            }
        }, internal_1.cdmStatusLevel.warning);
        const manifest = yield corpus.fetchObjectAsync('local:/entities.manifest.cdm.json');
        expect(manifest.entities.length)
            .toBe(1);
        expect(manifest.entities.allItems[0].objectType)
            .toBe(internal_1.cdmObjectType.localEntityDeclarationDef);
        const entity = manifest.entities.allItems[0];
        expect(entity.incrementalPartitionPatterns.length)
            .toBe(1);
        const incrementalPartitionPattern = entity.incrementalPartitionPatterns.allItems[0];
        expect(incrementalPartitionPattern.name)
            .toBe('UpsertPattern');
        expect(incrementalPartitionPattern.exhibitsTraits.length)
            .toBe(1);
        expect(incrementalPartitionPattern.exhibitsTraits.allItems[0].fetchObjectDefinitionName())
            .toBe(internal_1.constants.INCREMENTAL_TRAIT_NAME);
        expect(errorMessageVerified)
            .toBeTruthy();
    }));
    /**
     * Testing loading manifest with local entity declaration having a data partition pattern with incremental trait.
     */
    it('TestFromDataPartitionPatternWithIncrementalTrait', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = testHelper_1.testHelper.getLocalCorpus(testsSubpath, 'TestFromDataPartitionPatternWithIncrementalTrait');
        let errorMessageVerified = false;
        // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition)
        corpus.setEventCallback((level, message) => {
            if (message.indexOf('Failed to persist object \'UpsertPattern\'. This object contains the trait \'is.partition.incremental\', so it should not be in the collection \'dataPartitionPatterns\'. | fromData') !== -1) {
                errorMessageVerified = true;
            }
            else {
                throw new Error('Some unexpected failure - ' + message);
            }
        }, internal_1.cdmStatusLevel.warning);
        const manifest = yield corpus.fetchObjectAsync('local:/entities.manifest.cdm.json');
        expect(manifest.entities.length)
            .toBe(1);
        expect(manifest.entities.allItems[0].objectType)
            .toBe(internal_1.cdmObjectType.localEntityDeclarationDef);
        const entity = manifest.entities.allItems[0];
        expect(entity.dataPartitionPatterns.length)
            .toBe(1);
        expect(entity.dataPartitionPatterns.allItems[0].name)
            .toBe('TestingPattern');
        expect(errorMessageVerified)
            .toBeTruthy();
    }));
    /*
    * Testing saving manifest with local entity declaration having an incremental partition pattern without incremental trait.
    */
    it('TestToIncrementalPartitionPatternWithoutTrait', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = testHelper_1.testHelper.getLocalCorpus(testsSubpath, 'TestToIncrementalPartitionPatternWithoutTrait');
        let errorMessageVerified = false;
        // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition)
        corpus.setEventCallback((level, message) => {
            if (message.indexOf('Failed to persist object \'DeletePartitionPattern\'. This object does not contain the trait \'is.partition.incremental\', so it should not be in the collection \'incrementalPartitionPatterns\'. | toData') !== -1) {
                errorMessageVerified = true;
            }
            else {
                throw new Error('Some unexpected failure - ' + message);
            }
        }, internal_1.cdmStatusLevel.warning);
        const manifest = new internal_1.CdmManifestDefinition(corpus.ctx, 'manifest');
        corpus.storage.fetchRootFolder('local').documents.push(manifest);
        const entity = new internal_1.CdmEntityDefinition(corpus.ctx, 'entityName', undefined);
        (0, CdmCollectionHelperFunctions_1.createDocumentForEntity)(corpus, entity);
        const localizedEntityDeclaration = manifest.entities.push(entity);
        const upsertIncrementalPartitionPattern = corpus.MakeObject(internal_1.cdmObjectType.dataPartitionPatternDef, 'UpsertPattern', false);
        upsertIncrementalPartitionPattern.rootLocation = '/IncrementalData';
        upsertIncrementalPartitionPattern.regularExpression = '/(.*)/(.*)/(.*)/Upserts/upsert(\\d+)\\.csv$';
        upsertIncrementalPartitionPattern.parameters = ['year', 'month', 'day', 'upsertPartitionNumber'];
        upsertIncrementalPartitionPattern.exhibitsTraits.push(internal_1.constants.INCREMENTAL_TRAIT_NAME, [['type', internal_1.cdmIncrementalPartitionType[internal_1.cdmIncrementalPartitionType.Upsert]]]);
        const deletePartitionPattern = corpus.MakeObject(internal_1.cdmObjectType.dataPartitionPatternDef, 'DeletePartitionPattern', false);
        deletePartitionPattern.rootLocation = '/IncrementalData';
        deletePartitionPattern.regularExpression = '/(.*)/(.*)/(.*)/Delete/delete(\\d+)\\.csv$';
        deletePartitionPattern.parameters = ['year', 'month', 'day', 'detelePartitionNumber'];
        localizedEntityDeclaration.incrementalPartitionPatterns.push(upsertIncrementalPartitionPattern);
        localizedEntityDeclaration.incrementalPartitionPatterns.push(deletePartitionPattern);
        (0, using_statement_1.using)((0, internal_1.enterScope)('DataPartitionPatternTest', corpus.ctx, 'TestToIncrementalPartitionPatternWithoutTrait'), _ => {
            const manifestData = Persistence_1.CdmFolder.ManifestPersistence.toData(manifest, undefined, undefined);
            expect(manifestData.entities.length)
                .toBe(1);
            const entityData = manifestData.entities[0];
            expect(entityData.incrementalPartitionPatterns.length)
                .toBe(1);
            const patternData = entityData.incrementalPartitionPatterns[0];
            expect(patternData.name)
                .toBe('UpsertPattern');
            expect(patternData.exhibitsTraits.length)
                .toBe(1);
            expect(patternData.exhibitsTraits[0].traitReference)
                .toBe(internal_1.constants.INCREMENTAL_TRAIT_NAME);
        });
        expect(errorMessageVerified)
            .toBeTruthy();
    }));
    /*
    * Testing saving manifest with local entity declaration having a data partition pattern with incremental trait.
    */
    it('TestToDataPartitionPatternWithIncrementalTrait', () => __awaiter(void 0, void 0, void 0, function* () {
        const corpus = testHelper_1.testHelper.getLocalCorpus(testsSubpath, 'TestToDataPartitionPatternWithIncrementalTrait');
        let errorMessageVerified = false;
        // not checking the CdmLogCode here as we want to check if this error message constructed correctly for the partition pattern (it shares the same CdmLogCode with partition)
        corpus.setEventCallback((level, message) => {
            if (message.indexOf('Failed to persist object \'UpsertPartitionPattern\'. This object contains the trait \'is.partition.incremental\', so it should not be in the collection \'dataPartitionPatterns\'. | toData') !== -1) {
                errorMessageVerified = true;
            }
            else {
                throw new Error('Some unexpected failure - ' + message);
            }
        }, internal_1.cdmStatusLevel.warning);
        const manifest = new internal_1.CdmManifestDefinition(corpus.ctx, 'manifest');
        corpus.storage.fetchRootFolder('local').documents.push(manifest);
        const entity = new internal_1.CdmEntityDefinition(corpus.ctx, 'entityName', undefined);
        (0, CdmCollectionHelperFunctions_1.createDocumentForEntity)(corpus, entity);
        const localizedEntityDeclaration = manifest.entities.push(entity);
        const upsertIncrementalPartitionPattern = corpus.MakeObject(internal_1.cdmObjectType.dataPartitionPatternDef, 'UpsertPartitionPattern', false);
        upsertIncrementalPartitionPattern.rootLocation = '/IncrementalData';
        upsertIncrementalPartitionPattern.exhibitsTraits.push(internal_1.constants.INCREMENTAL_TRAIT_NAME, [['type', internal_1.cdmIncrementalPartitionType[internal_1.cdmIncrementalPartitionType.Upsert]]]);
        const deletePartitionPattern = corpus.MakeObject(internal_1.cdmObjectType.dataPartitionPatternDef, 'TestingPartitionPattern', false);
        deletePartitionPattern.rootLocation = '/IncrementalData';
        localizedEntityDeclaration.dataPartitionPatterns.push(upsertIncrementalPartitionPattern);
        localizedEntityDeclaration.dataPartitionPatterns.push(deletePartitionPattern);
        (0, using_statement_1.using)((0, internal_1.enterScope)('DataPartitionPatternTest', corpus.ctx, 'TestToDataPartitionPatternWithIncrementalTrait'), _ => {
            const manifestData = Persistence_1.CdmFolder.ManifestPersistence.toData(manifest, undefined, undefined);
            expect(manifestData.entities.length)
                .toBe(1);
            const entityData = manifestData.entities[0];
            expect(entityData.dataPartitionPatterns.length)
                .toBe(1);
            const patternData = entityData.dataPartitionPatterns[0];
            expect(patternData.name)
                .toBe('TestingPartitionPattern');
        });
        expect(errorMessageVerified)
            .toBeTruthy();
    }));
});
//# sourceMappingURL=DataPartitionPattern.test.js.map