"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionImageService = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@loopback/core");
const lodash_1 = require("lodash");
const services_1 = require("../../services");
const action_entity_service_1 = require("../../services/action-entity/action-entity.service");
const object_node_service_1 = require("../../services/object-node/object-node.service");
const location_service_1 = require("../location/location.service");
const application_error_1 = require("./../../helper/application-error");
const entity_name_1 = require("./../../models/entity-name");
const application_service_1 = require("./../../services/application.service");
const object_node_definition_service_1 = require("./../../services/entity-definition/object-node-definition.service");
const inside_rest_service_1 = require("./../../services/inside-rest/inside-rest.service");
const action_tree_service_1 = require("./../../services/object-tree/action-tree.service");
const object_type_service_1 = require("./../../services/object-type.service");
const transient_node_service_1 = require("./../../services/transient-entity/transient-node.service");
const uri_complete_service_1 = require("./../../services/uri-complete/uri-complete.service");
const content_image_const_1 = require("./content-image.const");
const content_image_definition_1 = require("./content-image.definition");
const intercept_image_service_1 = require("./intercept-image.service");
const transient_image_service_1 = require("./transient-image.service");
const objects_model_1 = require("@jacquesparis/objects-model");
const generated_response_1 = require("../../helper/generated-response");
const log_service_1 = require("../log/log.service");
const server_config_service_1 = require("../server-config/server-config.service");
class ImagesHolderEntry {
    constructor(imageHolder, includeChildren = true) {
        this.includeChildren = includeChildren;
        this.parentPath = imageHolder.path;
        this.treeId = imageHolder.tree.id;
        this.size = includeChildren ? imageHolder.totalSize : imageHolder.levelSize;
        this.name =
            imageHolder.tree.treeNode.title || imageHolder.tree.treeNode.name;
        this.filename = generated_response_1.normalizeFileName(this.parentPath + this.name + '.zip');
    }
}
class ImagesHolder {
    constructor(tree, parent) {
        this.tree = tree;
        this.parent = parent;
        this.totalSize = 0;
        this.levelSize = 0;
        this.level = 0;
        this.path = '';
        this.children = [];
        if (parent) {
            this.level = parent.level + 1;
            this.path =
                parent.path +
                    (parent.tree.treeNode.title || parent.tree.treeNode.name) +
                    '/';
            parent.children.push(this);
        }
    }
    addSize(size) {
        this.levelSize += size;
        this.addChildSize(size);
    }
    addChildSize(size) {
        this.totalSize += size;
        if (this.parent) {
            this.parent.addChildSize(size);
        }
    }
    getEntries(maxZipSize, entries) {
        if (!entries) {
            entries = [];
        }
        if (this.totalSize < maxZipSize) {
            if (0 < this.totalSize) {
                entries.push(new ImagesHolderEntry(this));
            }
            return entries;
        }
        if (this.levelSize > 0) {
            entries.push(new ImagesHolderEntry(this, false));
        }
        for (const child of this.children) {
            child.getEntries(maxZipSize, entries);
        }
        return entries;
    }
}
let ActionImageService = class ActionImageService {
    constructor(actionEntityService, objectNodeService, objectTypeService, insideRestService, uriCompleteService, objectNodeDefinitionService, transientImageService, interceptImageService, transientNodeService, locationService, objectTreeService, contentImageService, logService, serverConfigService) {
        this.actionEntityService = actionEntityService;
        this.objectNodeService = objectNodeService;
        this.objectTypeService = objectTypeService;
        this.insideRestService = insideRestService;
        this.uriCompleteService = uriCompleteService;
        this.objectNodeDefinitionService = objectNodeDefinitionService;
        this.transientImageService = transientImageService;
        this.interceptImageService = interceptImageService;
        this.transientNodeService = transientNodeService;
        this.locationService = locationService;
        this.objectTreeService = objectTreeService;
        this.contentImageService = contentImageService;
        this.logService = logService;
        this.serverConfigService = serverConfigService;
        this.actionEntityService.registerNewViewFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Load gallery in zip file', entity_name_1.EntityName.objectTree, 'zip', content_image_const_1.DISPLAYED_IMAGE_GALLERY_TYPE.name, this.downloadGallery.bind(this), 'read');
        this.actionEntityService.registerNewViewFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Load all galleries in zip file', entity_name_1.EntityName.objectTree, 'zipAll', content_image_const_1.IMAGE_GALLERIES_TYPE.name, this.downloadGalleries.bind(this), 'read');
        this.actionEntityService.registerNewMethodFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Load and create several Image entities in an Image Album', entity_name_1.EntityName.objectNode, 'load', content_image_const_1.IMAGE_ALBUM_TYPE.name, this.loadImageGalleryNode.bind(this), 'create');
        this.actionEntityService.registerNewMethodFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Load and create several Image entities in a referenced Image Gallery', entity_name_1.EntityName.objectNode, 'load', content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name, this.loadImageGalleryReferrerNode.bind(this), 'create');
        this.actionEntityService.registerNewViewFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Download referred images in zip file', entity_name_1.EntityName.objectNode, 'zip', content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name, this.downloadReferredImages.bind(this), 'read');
        this.actionEntityService.registerNewViewFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Download all content referred images in zip file', entity_name_1.EntityName.objectTree, 'zipAll', content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name, this.downloadContentImages.bind(this), 'read');
        this.actionEntityService.registerNewViewFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Download all content referred images in separated zip files', entity_name_1.EntityName.objectTree, 'zipAllFiles', content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name, this.downloadContentImagesFiles.bind(this), 'read');
        this.actionEntityService.registerNewMethodFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Create new Image Gallery for a gallery referrer', entity_name_1.EntityName.objectNode, 'createGallery', content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name, this.createGalleryImageGalleryReferrerNode.bind(this), 'create');
        this.actionEntityService.registerNewMethodFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Configure an Image Gallery for a gallery referrer', entity_name_1.EntityName.objectNode, 'configureGallery', content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name, this.configureGalleryImageGalleryReferrerNode.bind(this), 'update');
        this.actionEntityService.registerNewMethodFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Reset image position and/or date', entity_name_1.EntityName.objectNode, 'resetInfo', content_image_const_1.IMAGE_TYPE.name, this.resetInfoImageNode.bind(this), 'update');
        this.actionEntityService.registerNewMethodFunction(content_image_const_1.CONTENT_IMAGE_PROVIDER, ActionImageService.name, 'Reset images order', entity_name_1.EntityName.objectNode, 'resetOrder', content_image_const_1.IMAGE_ALBUM_TYPE.name, this.resetOrderImageGalleryNode.bind(this), 'update');
        this.locationService.registerLocationProvider({
            locatableItems: [
                {
                    objectType: content_image_const_1.IMAGE_GALLERY_REFERRER_TYPE.name,
                    entityType: entity_name_1.EntityName.objectNode,
                    treeItemsConditionField: 'selectedImages',
                    treeItemsField: 'images',
                    locationField: 'imagePosition',
                },
                {
                    objectType: content_image_const_1.IMAGE_GALLERY_TYPE.name,
                    entityType: entity_name_1.EntityName.objectTree,
                    treeItemsField: 'images',
                    locationField: 'imagePosition',
                },
            ],
        });
        this.serverConfigService.registerNewConfigurationKey('pctZipMaxSize', {
            type: 'number',
            title: 'Percentage max image zip file size (default 70)',
        });
    }
    async resetOrderImageGalleryNode(entity, args, ctx) {
        const galleryTree = await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, entity.id, ctx), ctx);
        await new action_tree_service_1.SortMethod(this.objectNodeService).runMethod(galleryTree, galleryTree.children
            .sort((a, b) => {
            if (!a.treeNode.imageDate && !b.treeNode.imageDate) {
                return a.treeNode.index - b.treeNode.index;
            }
            if (!a.treeNode.imageDate || !b.treeNode.imageDate) {
                return !a.treeNode.imageDate ? 1 : -1;
            }
            return Date.parse(a.treeNode.imageDate) <
                Date.parse(b.treeNode.imageDate)
                ? -1
                : 1;
        })
            .map((tree) => tree.treeNode.id), ctx);
        return this.actionEntityService.getEntity(entity_name_1.EntityName.objectTree, entity.id, application_service_1.CurrentContext.get(ctx, {}));
    }
    async resetInfoImageNode(entity, args, ctx) {
        if (args.position || args.date) {
            const update = {};
            if (entity.contentImageId && !entity.contentImage) {
                await this.transientNodeService.completeReturnedEntity(entity, ctx);
            }
            const exif = (await this.transientImageService.getImageExif(entity));
            if (args.position) {
                const imagePosition = this.transientImageService.getPositionFromExif(exif);
                if (imagePosition) {
                    update.imagePosition = imagePosition;
                }
            }
            if (args.date) {
                const imageDate = this.transientImageService.getImageDateFromExif(exif);
                if (imageDate) {
                    update.imageDate = imageDate;
                }
            }
            if (0 < Object.keys(update).length) {
                await this.objectNodeService.modifyById(entity.id, update, ctx);
            }
        }
        return this.actionEntityService.getEntity(entity_name_1.EntityName.objectNode, entity.id, application_service_1.CurrentContext.get(ctx, {}));
    }
    async createImage(image, parent, ctx, parentType, title) {
        await this.interceptImageService.checkAndReduceImageSize(image);
        const childCtx = application_service_1.CurrentContext.get(ctx, {
            nodeContext: {
                parent: new application_service_1.ExpectedValue(parent),
                parentType: new application_service_1.ExpectedValue(parentType),
            },
        });
        const nameParts = image.name.split('.');
        if (1 < nameParts.length) {
            nameParts.pop();
        }
        const exif = (await this.transientImageService.getImageExif({
            contentImage: image,
        }));
        const position = this.transientImageService.getPositionFromExif(exif);
        const date = this.transientImageService.getImageDateFromExif(exif);
        return this.objectNodeService.add({
            name: title ? title : nameParts.join('.'),
            imagePosition: position,
            imageDate: date,
            parentNodeId: parent.id,
            objectTypeId: content_image_const_1.IMAGE_TYPE.name,
            contentImage: image,
        }, childCtx, false, true, true);
    }
    async downloadImages(name, images, ctx, response, path = '') {
        if (!response) {
            response = new generated_response_1.ZipGeneratedResponse(name);
        }
        for (const image of images) {
            const content = await this.contentImageService.getContent({}, undefined, {
                contentId: image.original.contentImageId,
            });
            await this.serverConfigService.checkMemoryUsage();
            response.addBase64(path + content.name, content.base64);
            if (await this.logService.isDebug('DEBUG')) {
                if (!ctx.downloadImagesCtx) {
                    ctx.downloadImagesCtx = {
                        totalLength: 0,
                        nbFile: 0,
                    };
                }
                ctx.downloadImagesCtx.totalLength += content.base64.length;
                ctx.downloadImagesCtx.nbFile += 1;
                await this.logService.addLog('DEBUG', ActionImageService.name, 'downloadImages', `${path + content.name}, length ${content.base64.length}, added`, ctx, ctx.downloadImagesCtx);
            }
        }
        return response;
    }
    async downloadGalleries(galleries, args, ctx) {
        const response = new generated_response_1.ZipGeneratedResponse(galleries.treeNode.title || galleries.treeNode.name);
        for (const gallery of galleries.children) {
            await this.downloadGallery(gallery, args, ctx, response, (gallery.treeNode.title || gallery.treeNode.name) + '/');
        }
        return response;
    }
    async downloadGallery(tree, args, ctx, response, path = '') {
        const images = (await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, tree.id, ctx), ctx)).images;
        return this.downloadImages(tree.treeNode.title || tree.treeNode.name, images, ctx, response, path);
    }
    async downloadReferredImages(node, args, ctx, response, path = '') {
        if (!response) {
            if (args[0] && lodash_1.isString(args[0]) && args[0].length > 1) {
                path = args[0];
            }
            response = new generated_response_1.ZipGeneratedResponse(path + (node.title || node.name));
            if (path) {
                path += node.title || node.name;
            }
        }
        const images = (await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectNode, node.id, ctx), ctx)).images;
        return this.downloadImages(node.title || node.name, images, ctx, response, path);
    }
    async downloadContentImagesFiles(tree, args, ctx) {
        const maxZipFileSize = parseInt(args[0]);
        const imagesHolder = await this.buildImagesTree(tree, ctx);
        const entries = imagesHolder.getEntries(maxZipFileSize);
        let downloadZips = '';
        for (const entry of entries) {
            downloadZips += `
      <div class="card col-12 col-sm-6 col-md-4 col-lg-3 col-xl-3 col-xxl-2" id="entry${entry.treeId}">
        <div class="card-body">
          <h5 class="card-title">${entry.name}</h5>
          <h6 class="card-subtitle mb-2 text-muted">${entry.parentPath}</h6>
          <p class="card-text${maxZipFileSize < entry.size ? ' text-danger' : ''}">Images of ${entry.name} (${entry.includeChildren ? '' : 'not '}included sub contents) has a size of ${entry.size} bytes</p>
          <a target="_blank" onclick="window.setTimeout(()=>{document.getElementById('entry${entry.treeId}').remove()})"  href="${this.uriCompleteService.getUri(entry.includeChildren ? entity_name_1.EntityName.objectTree : entity_name_1.EntityName.objectNode, entry.treeId, ctx)}/view/${entry.includeChildren ? 'zipAll' : 'zip'}/${encodeURIComponent(entry.parentPath)}" class="card-link">Download ${entry.filename}</a>
      <a  onclick="window.setTimeout(()=>{document.getElementById('entry${entry.treeId}').remove()})" href="#" class="card-link">Cancel</a>

      </div>
      </div>
      `;
        }
        const htmlError = new generated_response_1.HtmlGeneratedResponse(`
    <!DOCTYPE html>
    <html>
      <head>
      <style>
      .card:not(:first-of-type)
        a {display:none;
    }

.card:not(:first-of-type){
  opacity:0.5
}
      </style>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css" />

        <link rel="stylesheet" href="/fontawesome/css/fontawesome.css" />
        <link rel="stylesheet" href="/fontawesome/css/regular.css" />
        <link rel="stylesheet" href="/fontawesome/css/solid.css" />

        <script src="/jquery/jquery.slim.min.js"></script>
        <script src="/bootstrap/js/bootstrap.bundle.min.js"></script>
      </head>
      <body>
        <h2 class="display-2">The Zip exceeds max size</h2>

        <div class="alert alert-warning" role="alert">
        The cumulated file size exceed ${maxZipFileSize} bytes.
        </div>
        <div class="row">
          ${downloadZips}
        </div>
      </body>
    </html>
`);
        return htmlError;
    }
    async buildImagesTree(tree, ctx, imagesTree) {
        if (!imagesTree) {
            imagesTree = new ImagesHolder(tree);
        }
        if (tree.treeNode.imageGalleryObjectTreeId) {
            await this.addImageToTree(ctx, imagesTree);
        }
        for (const child of tree.children) {
            await this.buildImagesTree(child, ctx, new ImagesHolder(child, imagesTree));
        }
        return imagesTree;
    }
    async addImageToTree(ctx, imagesTree) {
        const images = (await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectNode, imagesTree.tree.treeNode.id, ctx), ctx)).images;
        for (const image of images) {
            const content = await this.contentImageService.getContent({}, undefined, {
                contentId: image.original.contentImageId,
            });
            imagesTree.addSize(content.base64.length);
        }
    }
    async downloadContentImages(tree, args, ctx, response, path = '') {
        let recursiveCall = true;
        /**
         * Failed after :
         *
         * Las Bardenas Reales/Mercredi 26 octobre/Tudela/20221026_181109.jpg,
         * length 2529800,
         * added (totalLength = 525190748, nbFile = 186)
         * |  memoryUsage: (rss = 531013632, heapTotal = 202461184, heapUsed = 153659208, external = 412463114)"     */
        if (!response) {
            recursiveCall = false;
            if (args[0] && lodash_1.isString(args[0]) && args[0].length > 1) {
                path = args[0];
            }
            response = new generated_response_1.ZipGeneratedResponse(path + tree.treeNode.title || tree.treeNode.name);
            if (path) {
                path += tree.treeNode.title || tree.treeNode.name;
            }
        }
        try {
            if (tree.treeNode.imageGalleryObjectTreeId) {
                await this.downloadReferredImages(tree.treeNode, args, ctx, response, path);
            }
            for (const child of tree.children) {
                const title = child.treeNode.paragraphTitle || child.treeNode.pageTitle;
                await this.downloadContentImages(child, args, ctx, response, path + (title ? title + '/' : ''));
            }
        }
        catch (error) {
            if (!recursiveCall &&
                error instanceof application_error_1.ApplicationError &&
                error.errorCode === objects_model_1.APPLICATION_ERRORS.OUT_OF_MEMORY_ERROR.errorCode) {
                const maxZipFileSize = Math.ceil((response.addedBase64Size *
                    (await this.serverConfigService.get('pctZipMaxSize', async () => {
                        return 70;
                    }))) /
                    100);
                const baseUri = `${this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, tree.id, ctx)}/view/zipAllFiles/${maxZipFileSize}`;
                return new generated_response_1.RedirectGeneratedResponse(baseUri);
            }
            throw error;
        }
        return response;
    }
    async loadImageGalleryNode(gallery, args, ctx) {
        const images = args;
        for (const image of images.images) {
            await this.createImage(image, ctx.nodeContext.node.value, ctx, ctx.nodeContext.objectType.value, images.title);
        }
        return this.actionEntityService.getEntity(entity_name_1.EntityName.objectTree, gallery.id, application_service_1.CurrentContext.get(ctx, {}));
    }
    async configureGalleryImageGalleryReferrerNode(objectNode, args, ctx) {
        const imageGalleryObjectTreeId = args.imageGalleryObjectTreeId;
        if (undefined === imageGalleryObjectTreeId ||
            '' === imageGalleryObjectTreeId) {
            throw application_error_1.ApplicationError.missingParameter(imageGalleryObjectTreeId);
        }
        await this.objectNodeService.modifyById(objectNode.id, { imageGalleryObjectTreeId: imageGalleryObjectTreeId }, application_service_1.CurrentContext.get(ctx));
        return this.actionEntityService.getEntity(entity_name_1.EntityName.objectNode, objectNode.id, application_service_1.CurrentContext.get(ctx, {}));
    }
    async createGalleryImageGalleryReferrerNode(objectNode, args, ctx) {
        var _a, _b;
        const creationArguments = args;
        let name = creationArguments.name;
        if (!name || '' === name) {
            name = objectNode.title || objectNode.name;
        }
        let parentId = creationArguments.parentId;
        if (!parentId || '' === parentId) {
            const galleries = await this.transientImageService.getImageAlbumsParents(objectNode);
            if (!galleries || 0 === galleries.length) {
                throw application_error_1.ApplicationError.missing({ object: content_image_const_1.IMAGE_GALLERIES_TYPE.name });
            }
            parentId = galleries[0].id;
        }
        let childTypeId = creationArguments.childTypeId;
        const refererType = await this.objectTypeService.searchById(objectNode.objectTypeId);
        if (!refererType.definition.properties.imageGalleryObjectTreeId.oneOfTree) {
            throw application_error_1.ApplicationError.forbidden();
        }
        const oneOfTreeOptions = refererType.definition.properties.imageGalleryObjectTreeId.oneOfTree.filter((referencedTree) => !referencedTree.namespaceType);
        const referredTypes = oneOfTreeOptions.map((oneOfTree) => oneOfTree.treeType);
        let galleryTypes = [];
        for (const referredType of referredTypes) {
            galleryTypes.push(...(await this.objectTypeService.getImplementingTypes(referredType)));
        }
        if (!childTypeId || '' === childTypeId) {
            const parentGalleryTree = (await this.insideRestService.read(this.uriCompleteService.getUri(entity_name_1.EntityName.objectTree, parentId, ctx), ctx));
            if (!((_b = (_a = parentGalleryTree.entityCtx) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.creations)) {
                throw application_error_1.ApplicationError.missing({
                    object: content_image_const_1.IMAGE_GALLERIES_TYPE.name,
                    parentId: parentId,
                    childType: content_image_const_1.IMAGE_ALBUM_TYPE.name,
                });
            }
            const childTypeIds = Object.keys(parentGalleryTree.entityCtx.actions.creations);
            galleryTypes = galleryTypes.filter((type) => -1 < childTypeIds.indexOf(type));
            if (0 === childTypeIds.length) {
                throw application_error_1.ApplicationError.missing({
                    object: content_image_const_1.IMAGE_GALLERIES_TYPE.name,
                    parentId: parentId,
                    childType: content_image_const_1.IMAGE_ALBUM_TYPE.name,
                });
            }
            childTypeId = galleryTypes[0];
        }
        if (-1 === galleryTypes.indexOf(childTypeId)) {
            throw application_error_1.ApplicationError.unauthorizedValue({ childTypeId: childTypeId });
        }
        for (let index = oneOfTreeOptions.length - 1; index--; index >= 0) {
            if (-1 ===
                lodash_1.indexOf(await this.objectTypeService.getImplementingTypes(oneOfTreeOptions[index].treeType), childTypeId)) {
                oneOfTreeOptions.splice(index, 1);
            }
        }
        if (0 === oneOfTreeOptions.length) {
            throw application_error_1.ApplicationError.unauthorizedValue({ childTypeId: childTypeId });
        }
        const oneOfTreeOption = oneOfTreeOptions[0];
        const newGallery = await this.objectNodeService.add({ parentNodeId: parentId, objectTypeId: childTypeId, name: name }, application_service_1.CurrentContext.get(ctx), false, true, true);
        const owner = await this.objectNodeService.getNode(newGallery.parentOwnerId, application_service_1.CurrentContext.get(ctx));
        const namespace = await this.objectNodeService.getNode(newGallery.parentNamespaceId, application_service_1.CurrentContext.get(ctx));
        const imageGalleryObjectTreeId = this.objectNodeDefinitionService.getTreeIdFromTreeOption(oneOfTreeOption, owner, namespace, newGallery);
        await this.objectNodeService.modifyById(objectNode.id, { imageGalleryObjectTreeId: imageGalleryObjectTreeId }, application_service_1.CurrentContext.get(ctx));
        return [
            await this.actionEntityService.getEntity(entity_name_1.EntityName.objectTree, parentId, application_service_1.CurrentContext.get(ctx, {})),
            await this.actionEntityService.getEntity(entity_name_1.EntityName.objectNode, objectNode.id, application_service_1.CurrentContext.get(ctx, {})),
        ];
    }
    async loadImageGalleryReferrerNode(objectNode, args, ctx) {
        if (objectNode.imageGalleryObjectTreeId) {
            const imageGalleryParts = objectNode.imageGalleryObjectTreeId.split('/');
            const imageGalleryNode = await this.objectNodeService.searchTree(imageGalleryParts[1], imageGalleryParts[2], imageGalleryParts[3], imageGalleryParts[4], imageGalleryParts[5], imageGalleryParts[6]);
            if (imageGalleryNode) {
                let selectedImages = undefined;
                let initialSelectedImagesCount = 0;
                const implementedTypes = await this.objectTypeService.getImplementedTypes(objectNode.objectTypeId);
                if (-1 < lodash_1.indexOf(implementedTypes, content_image_const_1.IMAGE_GALLERY_SELECTOR_TYPE.name)) {
                    selectedImages = objectNode.selectedImages
                        ? objectNode.selectedImages
                        : [];
                    initialSelectedImagesCount = selectedImages.length;
                }
                const images = args;
                for (const image of images.images) {
                    const imageObject = await this.createImage(image, imageGalleryNode, ctx, undefined, images.title);
                    if (imageObject && selectedImages) {
                        selectedImages.push(imageObject.name);
                    }
                }
                if (selectedImages &&
                    selectedImages.length > initialSelectedImagesCount) {
                    await this.objectNodeService.modifyById(objectNode.id, { selectedImages }, ctx);
                }
                return [
                    await this.actionEntityService.getEntity(entity_name_1.EntityName.objectTree, imageGalleryNode.id, application_service_1.CurrentContext.get(ctx, {})),
                    await this.actionEntityService.getEntity(entity_name_1.EntityName.objectNode, objectNode.id, ctx),
                ];
            }
        }
    }
};
ActionImageService = tslib_1.__decorate([
    tslib_1.__param(0, core_1.service(action_entity_service_1.ActionEntityService)),
    tslib_1.__param(1, core_1.service(object_node_service_1.ObjectNodeService)),
    tslib_1.__param(2, core_1.service(object_type_service_1.ObjectTypeService)),
    tslib_1.__param(3, core_1.service(inside_rest_service_1.InsideRestService)),
    tslib_1.__param(4, core_1.service(uri_complete_service_1.UriCompleteService)),
    tslib_1.__param(5, core_1.service(object_node_definition_service_1.ObjectNodeDefinitionService)),
    tslib_1.__param(6, core_1.service(transient_image_service_1.TransientImageService)),
    tslib_1.__param(7, core_1.service(intercept_image_service_1.InterceptImageService)),
    tslib_1.__param(8, core_1.service(transient_node_service_1.TransientNodeService)),
    tslib_1.__param(9, core_1.service(location_service_1.LocationService)),
    tslib_1.__param(10, core_1.service(services_1.ObjectTreeService)),
    tslib_1.__param(11, core_1.service(content_image_definition_1.ContentImageService)),
    tslib_1.__param(12, core_1.service(log_service_1.LogService)),
    tslib_1.__param(13, core_1.service(server_config_service_1.ServerConfigService)),
    tslib_1.__metadata("design:paramtypes", [action_entity_service_1.ActionEntityService,
        object_node_service_1.ObjectNodeService,
        object_type_service_1.ObjectTypeService,
        inside_rest_service_1.InsideRestService,
        uri_complete_service_1.UriCompleteService,
        object_node_definition_service_1.ObjectNodeDefinitionService,
        transient_image_service_1.TransientImageService,
        intercept_image_service_1.InterceptImageService,
        transient_node_service_1.TransientNodeService,
        location_service_1.LocationService,
        services_1.ObjectTreeService,
        content_image_definition_1.ContentImageService,
        log_service_1.LogService,
        server_config_service_1.ServerConfigService])
], ActionImageService);
exports.ActionImageService = ActionImageService;
//# sourceMappingURL=action-image.service.js.map