"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 });
exports.LocalEntityDeclarationPersistence = void 0;
const __1 = require("..");
const internal_1 = require("../../internal");
const Logger_1 = require("../../Utilities/Logging/Logger");
const timeUtils = require("../../Utilities/timeUtils");
const extensionHelper = require("./ExtensionHelper");
class LocalEntityDeclarationPersistence {
    static fromData(ctx, documentFolder, dataObj, extensionTraitDefList, manifest) {
        return __awaiter(this, void 0, void 0, function* () {
            const localEntityDec = ctx.corpus.MakeObject(internal_1.cdmObjectType.localEntityDeclarationDef, dataObj.name);
            const localExtensionTraitDefList = [];
            const entityDoc = yield __1.ModelJson.DocumentPersistence.fromData(ctx, dataObj, extensionTraitDefList, localExtensionTraitDefList);
            documentFolder.documents.push(entityDoc);
            // Entity schema path is the path to the doc containing the entity definition.
            localEntityDec.entityPath = ctx.corpus.storage.createRelativeCorpusPath(`${entityDoc.atCorpusPath}/${dataObj.name}`, manifest);
            localEntityDec.explanation = dataObj.description;
            if (dataObj['cdm:lastFileStatusCheckTime'] !== undefined) {
                localEntityDec.lastFileStatusCheckTime = new Date(dataObj['cdm:lastFileStatusCheckTime']);
            }
            if (dataObj['cdm:lastFileModifiedTime'] !== undefined) {
                localEntityDec.lastFileModifiedTime = new Date(dataObj['cdm:lastFileModifiedTime']);
            }
            if (dataObj['cdm:lastChildFileModifiedTime'] !== undefined) {
                localEntityDec.lastChildFileModifiedTime = new Date(dataObj['cdm:lastChildFileModifiedTime']);
            }
            if (dataObj.isHidden === true) {
                const isHiddenTrait = ctx.corpus.MakeObject(internal_1.cdmObjectType.traitRef, 'is.hidden', true);
                isHiddenTrait.isFromProperty = true;
                localEntityDec.exhibitsTraits.push(isHiddenTrait);
            }
            // Add traits for schema entity info.
            if (dataObj.schemas) {
                const t2pm = new internal_1.traitToPropertyMap(localEntityDec);
                t2pm.updatePropertyValue('cdmSchemas', dataObj.schemas);
            }
            // Data partitions are part of the local entity, add them here.
            if (dataObj.partitions) {
                for (const element of dataObj.partitions) {
                    const cdmPartition = yield __1.ModelJson.DataPartitionPersistence.fromData(ctx, element, extensionTraitDefList, localExtensionTraitDefList, documentFolder);
                    if (cdmPartition !== undefined) {
                        localEntityDec.dataPartitions.push(cdmPartition);
                    }
                    else {
                        Logger_1.Logger.error(ctx, this.TAG, this.fromData.name, null, internal_1.cdmLogCode.ErrPersistModelJsonDocConversionError);
                        return undefined;
                    }
                }
            }
            const importDocs = yield extensionHelper.standardImportDetection(ctx, extensionTraitDefList, localExtensionTraitDefList);
            extensionHelper.addImportDocsToManifest(ctx, importDocs, entityDoc);
            return localEntityDec;
        });
    }
    static toData(instance, manifest, resOpt, options) {
        return __awaiter(this, void 0, void 0, function* () {
            // Fetch the document from entity schema.
            const localEntity = yield __1.ModelJson.DocumentPersistence.toData(instance.entityPath, manifest, resOpt, options, instance.ctx);
            if (localEntity !== undefined) {
                const t2pm = new internal_1.traitToPropertyMap(instance);
                const isHiddenTrait = t2pm.fetchTraitReference('is.hidden');
                if (!localEntity.description) {
                    localEntity.description = instance.explanation;
                }
                localEntity['cdm:lastFileStatusCheckTime'] = timeUtils.getFormattedDateString(instance.lastFileStatusCheckTime);
                localEntity['cdm:lastFileModifiedTime'] = timeUtils.getFormattedDateString(instance.lastFileModifiedTime);
                localEntity['cdm:lastChildFileModifiedTime'] = timeUtils.getFormattedDateString(instance.lastChildFileModifiedTime);
                if (isHiddenTrait !== undefined) {
                    localEntity.isHidden = true;
                }
                const schemas = t2pm.fetchPropertyValue('cdmSchemas');
                if (schemas !== undefined) {
                    localEntity.schemas = schemas;
                }
                if (instance.dataPartitions !== undefined && instance.dataPartitions.length > 0) {
                    localEntity.partitions = [];
                    for (const element of instance.dataPartitions) {
                        const partition = yield __1.ModelJson.DataPartitionPersistence.toData(element, resOpt, options);
                        if (partition !== undefined) {
                            localEntity.partitions.push(partition);
                        }
                    }
                }
                return localEntity;
            }
            return undefined;
        });
    }
    static copyExtensionProperties(entityFrom, entityDest) {
        for (const prop of Object.keys(entityFrom)
            .filter((x) => x.indexOf(':') !== -1)) {
            entityDest[prop] = entityFrom[prop];
        }
    }
}
exports.LocalEntityDeclarationPersistence = LocalEntityDeclarationPersistence;
LocalEntityDeclarationPersistence.TAG = LocalEntityDeclarationPersistence.name;
//# sourceMappingURL=LocalEntityDeclarationPersistence.js.map