"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContentImageThumbService = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@loopback/core");
const models_1 = require("../../models");
const application_service_1 = require("./../../services/application.service");
const node_intercept_service_1 = require("./../../services/entity-intercept/node-intercept.service");
const inside_rest_service_1 = require("./../../services/inside-rest/inside-rest.service");
const object_node_service_1 = require("./../../services/object-node/object-node.service");
const transient_entity_service_1 = require("./../../services/transient-entity/transient-entity.service");
const content_image_const_1 = require("./../content-image/content-image.const");
const content_image_definition_1 = require("./../content-image/content-image.definition");
const content_image_thumb_const_1 = require("./content-image-thumb.const");
const sharp = require('sharp');
let ContentImageThumbService = class ContentImageThumbService {
    constructor(transientEntityService, contentImageService, objectNodeService, insideRestService, nodeInterceptService) {
        /*
        this.transientEntityService.registerTransientEntityTypeFunction(
          CONTENT_IMAGE_THUMB_PROVIDER,
          ContentImageThumbService.name,
          'Build image Thumb and Web version',
          EntityName.objectNode,
          IMAGE_TYPE.name,
          this.completeImageNode.bind(this),
        );*/
        this.transientEntityService = transientEntityService;
        this.contentImageService = contentImageService;
        this.objectNodeService = objectNodeService;
        this.insideRestService = insideRestService;
        this.nodeInterceptService = nodeInterceptService;
        /*
        this.transientEntityService.registerTransientEntityTypeFunction(
          CONTENT_IMAGE_THUMB_PROVIDER,
          ContentImageThumbService.name,
          'Build images Thumb and Web version',
          EntityName.objectTree,
          IMAGE_GALLERY_TYPE.name,
          this.completeImageGalleryTree.bind(this),
        );
        */
        this.transientEntityService.registerTransientEntityTypeFunction(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Build image Thumb and Web version', models_1.EntityName.objectTree, content_image_const_1.IMAGE_TYPE.name, this.completeImageTree.bind(this));
        this.transientEntityService.registerTransientEntityTypeFunction(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Change thumb image Access Rights', models_1.EntityName.objectTree, content_image_thumb_const_1.IMAGE_THUMB_TYPE.name, this.completeImageThumbAndImageOriginalNodeOrTree.bind(this));
        this.transientEntityService.registerTransientEntityTypeFunction(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Change original image Access Rights', models_1.EntityName.objectTree, content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name, this.completeImageThumbAndImageOriginalNodeOrTree.bind(this));
        this.transientEntityService.registerTransientEntityTypeFunction(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Change thumb image Access Rights', models_1.EntityName.objectNode, content_image_thumb_const_1.IMAGE_THUMB_TYPE.name, this.completeImageThumbAndImageOriginalNodeOrTree.bind(this));
        this.transientEntityService.registerTransientEntityTypeFunction(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Change original image Access Rights', models_1.EntityName.objectNode, content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name, this.completeImageThumbAndImageOriginalNodeOrTree.bind(this));
        this.transientEntityService.registerTransientEntityTypeFunction(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Trigger on POST, PUT and PATCH thumb and web image generation', models_1.EntityName.objectNode, content_image_const_1.IMAGE_TYPE.name, this.completeImageNode.bind(this), ['PATCH', 'POST', 'PUT']);
        this.nodeInterceptService.registerEntityInterceptorService(content_image_thumb_const_1.CONTENT_IMAGE_THUMB_PROVIDER, ContentImageThumbService.name, 'Delete image Thumb and Original version', content_image_const_1.IMAGE_TYPE.name, application_service_1.EntityActionType.update, this.interceptImageNodeUpdate.bind(this));
    }
    async interceptImageNodeUpdate(entityId, entity, requestEntity, ctx) {
        await this.objectNodeService.removeByParent(object_node_service_1.ParentNodeType.node, entityId ? entityId : entity.id, ctx);
        return true;
    }
    async completeImageNode(image, ctx) {
        var _a;
        if (image.uri) {
            try {
                await this.insideRestService.read((_a = image.uri) === null || _a === void 0 ? void 0 : _a.replace('object-nodes', 'object-trees'), ctx, true);
            }
            catch (error) { }
        }
    }
    async completeImageThumbAndImageOriginalNodeOrTree(image, ctx) {
        var _a, _b, _c, _d;
        const rights = (_b = (_a = image.entityCtx) === null || _a === void 0 ? void 0 : _a.aclCtx) === null || _b === void 0 ? void 0 : _b.rights;
        if (rights) {
            rights.create = false;
            rights.delete = false;
            rights.update = false;
        }
        if (image.treeNode) {
            const nodeRights = (_d = (_c = image.treeNode.entityCtx) === null || _c === void 0 ? void 0 : _c.aclCtx) === null || _d === void 0 ? void 0 : _d.rights;
            if (nodeRights) {
                nodeRights.create = false;
                nodeRights.delete = false;
                nodeRights.update = false;
            }
        }
    }
    async completeImageTree(imageTree, ctx) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        let hasNewNodes = false;
        if (!(content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name in imageTree.childrenByObjectTypeId)) {
            await this.contentImageService.addTransientContent(imageTree.treeNode);
            try {
                if (!imageTree.treeNode.contentImage ||
                    !imageTree.treeNode.contentImage.base64) {
                    //return hasNewNodes;
                    return;
                }
                await this.objectNodeService.add({
                    name: 'original_' + imageTree.treeNode.name,
                    parentNodeId: imageTree.treeNode.id,
                    objectTypeId: content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name,
                    contentImage: {
                        base64: imageTree.treeNode.contentImage.base64,
                        size: imageTree.treeNode.contentImage.size,
                        name: imageTree.treeNode.contentImage.name,
                        type: imageTree.treeNode.contentImage.type,
                    },
                }, application_service_1.CurrentContext.get(ctx, {
                    nodeContext: {
                        parent: new application_service_1.ExpectedValue(imageTree.treeNode),
                    },
                }));
                const newSize = await this.changeImgSize(imageTree.treeNode.contentImage, 800);
                await this.objectNodeService.modifyById(imageTree.treeNode.id, {
                    contentImage: {
                        base64: newSize.base64,
                        size: newSize.size,
                        name: imageTree.treeNode.contentImage.name,
                        type: imageTree.treeNode.contentImage.type,
                    },
                }, application_service_1.CurrentContext.get(ctx, {
                    nodeContext: {
                        node: new application_service_1.ExpectedValue(imageTree.treeNode),
                    },
                }));
            }
            catch (error) {
            }
            finally {
                hasNewNodes = true;
            }
        }
        if (!(content_image_thumb_const_1.IMAGE_THUMB_TYPE.name in imageTree.childrenByObjectTypeId)) {
            if (!imageTree.treeNode.contentImage ||
                !imageTree.treeNode.contentImage.base64) {
                await this.contentImageService.addTransientContent(imageTree.treeNode);
            }
            if (!imageTree.treeNode.contentImage ||
                !imageTree.treeNode.contentImage.base64) {
                //   return hasNewNodes;
                return;
            }
            const newSize = await this.changeImgSize(imageTree.treeNode.contentImage, 200);
            try {
                await this.objectNodeService.add({
                    name: 'thumb_' + imageTree.treeNode.name,
                    parentNodeId: imageTree.treeNode.id,
                    objectTypeId: content_image_thumb_const_1.IMAGE_THUMB_TYPE.name,
                    contentImage: {
                        base64: newSize.base64,
                        size: newSize.size,
                        name: imageTree.treeNode.contentImage.name,
                        type: imageTree.treeNode.contentImage.type,
                    },
                }, application_service_1.CurrentContext.get(ctx, {
                    nodeContext: {
                        parent: new application_service_1.ExpectedValue(imageTree.treeNode),
                    },
                }));
            }
            catch (error) {
            }
            finally {
                hasNewNodes = true;
            }
        }
        //   if (reloadTree && hasNewNodes) {
        if (hasNewNodes) {
            try {
                const newImage = await this.insideRestService.read(imageTree.uri, ctx, true);
                Object.assign(imageTree, newImage);
            }
            catch (_j) { }
        }
        else {
            if (content_image_thumb_const_1.IMAGE_THUMB_TYPE.name in imageTree.childrenByObjectTypeId) {
                imageTree.thumb =
                    imageTree.childrenByObjectTypeId[content_image_thumb_const_1.IMAGE_THUMB_TYPE.name][0].treeNode;
                const treeRights = (_b = (_a = imageTree.childrenByObjectTypeId[content_image_thumb_const_1.IMAGE_THUMB_TYPE.name][0].entityCtx) === null || _a === void 0 ? void 0 : _a.aclCtx) === null || _b === void 0 ? void 0 : _b.rights;
                if (treeRights) {
                    treeRights.create = false;
                    treeRights.delete = false;
                    treeRights.update = false;
                }
                const nodeRights = (_d = (_c = imageTree.childrenByObjectTypeId[content_image_thumb_const_1.IMAGE_THUMB_TYPE.name][0].treeNode
                    .entityCtx) === null || _c === void 0 ? void 0 : _c.aclCtx) === null || _d === void 0 ? void 0 : _d.rights;
                if (nodeRights) {
                    nodeRights.create = false;
                    nodeRights.delete = false;
                    nodeRights.update = false;
                }
            }
            if (content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name in imageTree.childrenByObjectTypeId) {
                imageTree.original =
                    imageTree.childrenByObjectTypeId[content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name][0].treeNode;
                const treeRights = (_f = (_e = imageTree.childrenByObjectTypeId[content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name][0]
                    .entityCtx) === null || _e === void 0 ? void 0 : _e.aclCtx) === null || _f === void 0 ? void 0 : _f.rights;
                if (treeRights) {
                    treeRights.create = false;
                    treeRights.delete = false;
                    treeRights.update = false;
                }
                const nodeRights = (_h = (_g = imageTree.childrenByObjectTypeId[content_image_thumb_const_1.IMAGE_ORIGINAL_TYPE.name][0].treeNode
                    .entityCtx) === null || _g === void 0 ? void 0 : _g.aclCtx) === null || _h === void 0 ? void 0 : _h.rights;
                if (nodeRights) {
                    nodeRights.create = false;
                    nodeRights.delete = false;
                    nodeRights.update = false;
                }
            }
        }
        //return hasNewNodes;
        return;
    }
    async completeImageGalleryTree(imageGallery, ctx) {
        // let hasNewNodes = false;
        for (const image of imageGallery.children) {
            /*
            hasNewNodes =
              hasNewNodes ||
              (await this._completeImageTree(image as ImageTree, ctx, false));*/
            await this.completeImageTree(image, ctx);
        }
        /*
        if (hasNewNodes) {
          const newGallery = await this.insideRestService.read(
            imageGallery.uri,
            ctx,
            true,
          );
          assign(imageGallery, newGallery);
        } else {
          for (const image of imageGallery.children) {
            image.thumb =
              image.childrenByObjectTypeId[IMAGE_THUMB_TYPE.name][0].treeNode;
            image.original =
              image.childrenByObjectTypeId[IMAGE_ORIGINAL_TYPE.name][0].treeNode;
          }
        }*/
    }
    /*
    public async completeImageNode(image: Image): Promise<void> {
      await this.contentImageService.addTransientContent(image);
      const img: Sharp = sharp(Buffer.from(image.contentImage.base64, 'base64'));
      img.resize(200, 200, {});
      image.contentImage.base64 = (await img.toBuffer()).toString('base64');
    }*/
    async changeImgSize(contentImage, size) {
        let img = sharp(Buffer.from(contentImage.base64, 'base64'));
        let width = size;
        let height = size;
        const metadata = await img.metadata();
        if (metadata.width && metadata.height) {
            const maxSize = Math.max(metadata.width, metadata.height);
            if (maxSize <= size) {
                return contentImage;
            }
            width = Math.ceil((metadata.width * size) / maxSize);
            height = Math.ceil((metadata.height * size) / maxSize);
        }
        img = img
            .resize(width, height, {
            fit: 'contain',
            background: { r: 255, g: 255, b: 255, alpha: 1 },
        })
            .withMetadata();
        const newMetadata = await img.metadata();
        return {
            base64: (await img.toBuffer()).toString('base64'),
            size: '' + newMetadata.size,
        };
    }
};
ContentImageThumbService = tslib_1.__decorate([
    tslib_1.__param(0, core_1.service(transient_entity_service_1.TransientEntityService)),
    tslib_1.__param(1, core_1.service(content_image_definition_1.ContentImageService)),
    tslib_1.__param(2, core_1.service(object_node_service_1.ObjectNodeService)),
    tslib_1.__param(3, core_1.service(inside_rest_service_1.InsideRestService)),
    tslib_1.__param(4, core_1.service(node_intercept_service_1.NodeInterceptService)),
    tslib_1.__metadata("design:paramtypes", [transient_entity_service_1.TransientEntityService,
        content_image_definition_1.ContentImageService,
        object_node_service_1.ObjectNodeService,
        inside_rest_service_1.InsideRestService,
        node_intercept_service_1.NodeInterceptService])
], ContentImageThumbService);
exports.ContentImageThumbService = ContentImageThumbService;
//# sourceMappingURL=content-image-thumb.service.js.map