"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.EntityReferencePersistence = void 0;
const __1 = require("..");
const internal_1 = require("../../internal");
const cdmObjectRefPersistence_1 = require("./cdmObjectRefPersistence");
const ProjectionPersistence_1 = require("./Projections/ProjectionPersistence");
const utils = require("./utils");
function isConstantEntity(object) {
    return 'entityShape' in object;
}
class EntityReferencePersistence extends cdmObjectRefPersistence_1.cdmObjectRefPersistence {
    static fromData(ctx, object) {
        if (!object) {
            return;
        }
        let simpleReference = true;
        let entity;
        let appliedTraits;
        if (typeof (object) === 'string') {
            entity = object;
        }
        else {
            simpleReference = false;
            entity = this.getEntityReference(ctx, object);
        }
        const entityReference = ctx.corpus.MakeRef(internal_1.cdmObjectType.entityRef, entity, simpleReference);
        if (typeof (object) !== 'string' && 'appliedTraits' in object) {
            appliedTraits = utils.createTraitReferenceArray(ctx, object.appliedTraits);
        }
        if (appliedTraits) {
            utils.addArrayToCdmCollection(entityReference.appliedTraits, appliedTraits);
        }
        return entityReference;
    }
    static toData(instance, resOpt, options) {
        if (instance.explicitReference !== undefined && instance.explicitReference instanceof internal_1.CdmProjection) {
            return ProjectionPersistence_1.ProjectionPersistence.toData(instance.explicitReference, resOpt, options);
        }
        else {
            return cdmObjectRefPersistence_1.cdmObjectRefPersistence.toData(instance, resOpt, options);
        }
    }
    static getEntityReference(ctx, object) {
        let entity = undefined;
        if ('entityReference' in object) {
            if (typeof (object.entityReference) === 'string') {
                entity = object.entityReference;
            }
            else if (isConstantEntity(object.entityReference)) {
                entity = __1.CdmFolder.ConstantEntityPersistence.fromData(ctx, object.entityReference);
            }
            else {
                entity = __1.CdmFolder.EntityPersistence.fromData(ctx, object.entityReference);
            }
        }
        else if ('source' in object || 'operations' in object) {
            entity = ProjectionPersistence_1.ProjectionPersistence.fromData(ctx, object);
        }
        return entity;
    }
}
exports.EntityReferencePersistence = EntityReferencePersistence;
//# sourceMappingURL=EntityReferencePersistence.js.map