"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.DocumentPersistence = void 0;
const __1 = require("..");
const internal_1 = require("../../internal");
const cdmObjectTypeGuards_1 = require("../../Utilities/cdmObjectTypeGuards");
const Logger_1 = require("../../Utilities/Logging/Logger");
class DocumentPersistence {
    static fromData(ctx, dataObj, extensionTraitDefList, localExtensionTraitDefList) {
        return __awaiter(this, void 0, void 0, function* () {
            const docName = `${dataObj.name}.cdm.json`;
            const doc = ctx.corpus.MakeObject(internal_1.cdmObjectType.documentDef, docName);
            // import at least foundations
            doc.imports.push('cdm:/foundations.cdm.json');
            const entityDec = yield __1.ModelJson.EntityPersistence.fromData(ctx, dataObj, extensionTraitDefList, localExtensionTraitDefList);
            if (!entityDec) {
                Logger_1.Logger.error(ctx, this.TAG, this.fromData.name, null, internal_1.cdmLogCode.ErrPersistModelJsonEntityConversionError, dataObj.name);
                return undefined;
            }
            if (dataObj['cdm:imports']) {
                for (const element of dataObj['cdm:imports']) {
                    if (element.corpusPath === 'cdm:/foundations.cdm.json') {
                        // don't add foundations twice
                        continue;
                    }
                    doc.imports.push(__1.CdmFolder.ImportPersistence.fromData(ctx, element));
                }
            }
            doc.definitions.push(entityDec);
            return doc;
        });
    }
    static toData(documentObjectOrPath, manifest, resOpt, options, ctx) {
        return __awaiter(this, void 0, void 0, function* () {
            if (typeof documentObjectOrPath === 'string') {
                // Fetch the document from entity schema.
                const cdmEntity = yield ctx.corpus.fetchObjectAsync(documentObjectOrPath, manifest);
                if (!cdmEntity) {
                    Logger_1.Logger.error(ctx, this.TAG, this.toData.name, manifest.atCorpusPath, internal_1.cdmLogCode.ErrPersistCdmEntityFetchError);
                    return undefined;
                }
                const entity = yield __1.ModelJson.EntityPersistence.toData(cdmEntity, resOpt, options, ctx);
                if (cdmObjectTypeGuards_1.isDocumentDefinition(cdmEntity.owner)) {
                    const document = cdmEntity.owner;
                    if (document.imports.length > 0) {
                        entity['cdm:imports'] = [];
                        for (const element of document.imports) {
                            const currImport = __1.CdmFolder.ImportPersistence.toData(element, resOpt, options);
                            // the corpus path in the imports are relative to the document where it was defined.
                            // when saving in model.json the documents are flattened to the manifest level
                            // so it is necessary to recalculate the path to be relative to the manifest.
                            let absolutePath = ctx.corpus.storage.createAbsoluteCorpusPath(currImport.corpusPath, document);
                            if (document.namespace && absolutePath.startsWith(`${document.namespace}:`)) {
                                absolutePath = absolutePath.substring(document.namespace.length + 1);
                            }
                            currImport.corpusPath = ctx.corpus.storage.createRelativeCorpusPath(absolutePath, manifest);
                            entity['cdm:imports'].push(currImport);
                        }
                    }
                }
                else {
                    Logger_1.Logger.warning(ctx, this.TAG, this.toData.name, manifest.atCorpusPath, internal_1.cdmLogCode.WarnPersistEntityMissing, cdmEntity.getName());
                }
                return entity;
            }
            else {
                // TODO: Do something else when documentObjectOrPath is an object.
            }
            return undefined;
        });
    }
}
exports.DocumentPersistence = DocumentPersistence;
DocumentPersistence.TAG = DocumentPersistence.name;
//# sourceMappingURL=DocumentPersistence.js.map