"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransientFileService = void 0;
const tslib_1 = require("tslib");
/* eslint-disable no-empty */
const core_1 = require("@loopback/core");
const lodash_1 = require("lodash");
const helper_1 = require("../../helper");
const entity_name_1 = require("../../models/entity-name");
const services_1 = require("../../services");
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 object_type_service_1 = require("../../services/object-type.service");
const transient_entity_service_1 = require("../../services/transient-entity/transient-entity.service");
const uri_complete_service_1 = require("../../services/uri-complete/uri-complete.service");
const content_file_const_1 = require("./content-file.const");
const content_file_definition_1 = require("./content-file.definition");
let TransientFileService = class TransientFileService {
    constructor(transientEntityService, insideRestService, uriCompleteService, contentFileService, objectTreeService, objectNodeService, objectTypeService) {
        this.transientEntityService = transientEntityService;
        this.insideRestService = insideRestService;
        this.uriCompleteService = uriCompleteService;
        this.contentFileService = contentFileService;
        this.objectTreeService = objectTreeService;
        this.objectNodeService = objectNodeService;
        this.objectTypeService = objectTypeService;
        this.transientEntityService.registerTransientEntityTypeFunction(content_file_const_1.CONTENT_FILE_PROVIDER, TransientFileService.name, 'Add referenced files field and its json schema definition. Add load Files method. Add create Directory method.', entity_name_1.EntityName.objectNode, content_file_const_1.FILE_DIRECTORY_REFERRER_TYPE.name, this.completeFileDirectoryReferrerNode.bind(this));
        this.transientEntityService.registerTransientEntityTypeFunction(content_file_const_1.CONTENT_FILE_PROVIDER, TransientFileService.name, 'Add load Files method definition to load several files in one operation and reset files position and date info method', entity_name_1.EntityName.objectNode, content_file_const_1.FILES_DIRECTORY_TYPE.name, this.completeFileDirectoryTypeNode.bind(this));
        /*
        this.transientEntityService.registerTransientEntityTypeFunction(
          CONTENT_FILE_PROVIDER,
          TransientFileService.name,
          'Add all files of the directory as referenced files',
          EntityName.objectTree,
          DISPLAYED_FILE_DIRECTORY_TYPE.name,
          this.completeDisplayedFileDirectoryTree.bind(this),
        );
        this.transientEntityService.registerTransientEntityTypeFunction(
          CONTENT_FILE_PROVIDER,
          TransientFileService.name,
          'Add all files of the all referenced directories',
          EntityName.objectTree,
          FILE_DIRECTORY_CONCATENATION_TYPE.name,
          this.completeFileDirectoryConcatenationTree.bind(this),
        );
    
        this.transientEntityService.registerTransientEntityTypeFunction(
          CONTENT_FILE_PROVIDER,
          TransientEntityService.name,
          'Add file EXIF info and reset info method',
          EntityName.objectNode,
          FILE_TYPE.name,
          this.completeFileTypeNode.bind(this),
        );
        */
    }
    /*
    public async completeDisplayedFileDirectoryTree(
      entity: ObjectTree,
      ctx: CurrentContext,
    ) {
      const files: ObjectTree[] = (
        await this.objectTreeService.getChildrenByImplementedTypeId(entity)
      )[FILE_TYPE.name];
      entity.files = files ? files : [];
    }
    */
    /*
    public async completeFileDirectoryConcatenationTree(
      entity: ObjectTree,
      ctx: CurrentContext,
    ) {
      entity.files = [];
      if (
        (
          await this.objectTypeService.getImplementedTypes(
            entity.treeNode.objectTypeId,
          )
        ).includes(FILE_DIRECTORY_CONCATENATION_ALL_DEFAULT_TYPE.name) &&
        !entity.treeNode.selectDirectories
      ) {
        const directoryTrees = await this.objectNodeService.searchTreesOfNamespaceId(
          entity.treeNode.parentNamespaceId,
          FILES_DIRECTORY_TYPE.name,
        );
        entity.treeNode.selectedGalleriesObjectTreeUris = directoryTrees.map(
          (directoryNode) =>
            this.uriCompleteService.getUri(
              EntityName.objectTree,
              directoryNode.id as string,
              ctx,
            ),
        );
      }
      if (entity.treeNode.selectedGalleriesObjectTreeUris) {
        for (const directoryTreeUri of entity.treeNode
          .selectedGalleriesObjectTreeUris) {
          const directoryTree: ObjectTree = await this.insideRestService.read<ObjectTree>(
            directoryTreeUri,
            ctx,
          );
          if (directoryTree.files) {
            entity.files.push(...directoryTree.files);
          }
        }
      }
    }
    */
    async completeFileDirectoryTypeNode(objectNode, ctx) {
        var _a;
        if (!objectNode.entityCtx) {
            objectNode.entityCtx = { entityType: entity_name_1.EntityName.objectNode };
        }
        if (!((_a = objectNode.entityCtx) === null || _a === void 0 ? void 0 : _a.actions)) {
            objectNode.entityCtx.actions = {};
        }
        if (!objectNode.entityCtx.actions.methods) {
            objectNode.entityCtx.actions.methods = [];
        }
        await this.addLoadFilesJsonSchemaMethod(objectNode, ctx);
    }
    async getFileDirectoriesParents(objectNode) {
        const directoriesType = await this.objectTypeService.getParentTypesOfImplementingType(content_file_const_1.FILES_DIRECTORY_TYPE.name);
        return this.objectNodeService.searchByParentNamespaceId(objectNode.parentNamespaceId, {
            objectTypeIds: directoriesType,
        });
    }
    async addCreateFilesDirectoryJsonSchemaMethod(objectNode, ctx) {
        var _a, _b, _c, _d, _e, _f, _g;
        if (!objectNode.entityCtx) {
            objectNode.entityCtx = { entityType: entity_name_1.EntityName.objectNode };
        }
        if (!((_a = objectNode.entityCtx) === null || _a === void 0 ? void 0 : _a.actions)) {
            objectNode.entityCtx.actions = {};
        }
        if (!objectNode.entityCtx.actions.methods) {
            objectNode.entityCtx.actions.methods = [];
        }
        const fileGalleries = await this.getFileDirectoriesParents(objectNode);
        if (fileGalleries && 0 < fileGalleries.length) {
            objectNode.entityCtx.actions.methods.push({
                methodId: 'createDirectory',
                methodName: 'Add files',
                actionName: 'Load files',
                parameters: {
                    type: 'object',
                    properties: {
                        useExistingDirectory: {
                            type: 'boolean',
                            title: 'Use existing directory',
                        },
                        name: {
                            type: 'string',
                            title: 'Directory name',
                            'x-schema-form': {
                                type: 'conditional-text',
                                conditionalValue: {
                                    title: 'Specify a directory name',
                                    defaultValue: `return ${JSON.stringify(objectNode.title)}`,
                                },
                            },
                        },
                    },
                },
                handlebarsMethodSampling: `[
          {{^useExistingDirectory}}
            {
              "methodId": "createDirectory",
              "parameters":{
                "name": {{&json name}},
                "parentId": {{&json parentId}}
              }
            }
          {{/useExistingDirectory}}
          {{#useExistingDirectory}}
            {
              "methodId": "configureDirectory",
              "parameters":{
                "fileDirectoryObjectTreeId": {{&json fileDirectoryObjectTreeId}}
              }
            }
          {{/useExistingDirectory}}
          {{#files}},
          {
            "methodId":"load",
            "parameters": {
              "title": {{&json ../title}},
              "files": [
                {{&json this}}
              ]
            }
          }{{/files}}
          ]`,
                icon: 'far fa-files',
            });
            const properties = objectNode.entityCtx.actions.methods[objectNode.entityCtx.actions.methods.length - 1].parameters.properties;
            if (1 < fileGalleries.length) {
                properties.parentId = {
                    type: 'string',
                    title: 'Galleries parent',
                    required: true,
                    oneOf: fileGalleries.map((directory) => ({
                        enum: [directory.id],
                        title: directory.name,
                    })),
                };
            }
            if (((_e = (_d = (_c = (_b = objectNode.entityCtx) === null || _b === void 0 ? void 0 : _b.jsonSchema) === null || _c === void 0 ? void 0 : _c.properties.fileDirectoryObjectTreeId) === null || _d === void 0 ? void 0 : _d.oneOf) === null || _e === void 0 ? void 0 : _e.length) > 0) {
                helper_1.addCondition('true !== model.useExistingDirectory', properties.name);
                if (properties.parentId) {
                    helper_1.addCondition('true !== model.useExistingDirectory', properties.parentId);
                }
                properties.fileDirectoryObjectTreeId = lodash_1.cloneDeep((_g = (_f = objectNode.entityCtx) === null || _f === void 0 ? void 0 : _f.jsonSchema) === null || _g === void 0 ? void 0 : _g.properties.fileDirectoryObjectTreeId);
                properties.fileDirectoryObjectTreeId.required = true;
                helper_1.addCondition('true === model.useExistingDirectory', properties.fileDirectoryObjectTreeId);
            }
            else {
                delete properties.useExistingDirectory;
            }
            properties.title = {
                type: 'string',
                title: 'Displayed name',
                'x-schema-form': {
                    type: 'conditional-text',
                    conditionalValue: {
                        title: 'Specify a label for files',
                        defaultValue: `return ${JSON.stringify(objectNode.title)}`,
                    },
                },
                default: objectNode.title,
            };
            helper_1.addCondition('(true === model.useExistingDirectory && model.fileDirectoryObjectTreeId) || !model.useExistingDirectory', properties.title);
            properties.files = {
                type: 'array',
                'x-schema-form': {
                    type: 'files',
                },
                items: (await this.contentFileService.getContentDefinition()).properties
                    .contentFile,
            };
            helper_1.addCondition('(true === model.useExistingDirectory && model.fileDirectoryObjectTreeId) || !model.useExistingDirectory', properties.files);
        }
    }
    async addLoadFilesJsonSchemaMethod(objectNode, ctx) {
        var _a;
        if (!objectNode.entityCtx) {
            objectNode.entityCtx = { entityType: entity_name_1.EntityName.objectNode };
        }
        if (!((_a = objectNode.entityCtx) === null || _a === void 0 ? void 0 : _a.actions)) {
            objectNode.entityCtx.actions = {};
        }
        if (!objectNode.entityCtx.actions.methods) {
            objectNode.entityCtx.actions.methods = [];
        }
        objectNode.entityCtx.actions.methods.push({
            methodId: 'load',
            methodName: 'Add files',
            actionName: 'Load files',
            parameters: {
                type: 'object',
                properties: {
                    title: {
                        type: 'string',
                        title: 'Displayed name',
                        'x-schema-form': {
                            type: 'conditional-text',
                            conditionalValue: {
                                title: 'Specify a label for files',
                                defaultValue: `return ${JSON.stringify(objectNode.title)}`,
                            },
                        },
                        default: objectNode.title,
                    },
                    files: {
                        type: 'array',
                        'x-schema-form': {
                            type: 'files',
                        },
                        items: (await this.contentFileService.getContentDefinition())
                            .properties.contentFile,
                    },
                },
            },
            handlebarsMethodSampling: `[{{#files}}
          {
            "methodId":"load",
            "parameters": {
              "title": {{&json ../title}},
              "files": [
                {{&json this}}
              ]
            }
          }{{#unless @last}},{{/unless}}{{/files}}
        ]`,
            icon: 'far fa-files',
        });
    }
    async completeFileDirectoryReferrerNode(objectNode, ctx) {
        var _a, _b, _c, _d, _e;
        const files = [];
        if (!objectNode.fileDirectoryTree &&
            objectNode.fileDirectoryObjectTreeUri) {
            try {
                objectNode.fileDirectoryTree = (await this.insideRestService.read(objectNode.fileDirectoryObjectTreeUri, ctx));
            }
            catch (error) { }
        }
        if ((_a = objectNode.fileDirectoryTree) === null || _a === void 0 ? void 0 : _a.children) {
            for (const file of objectNode.fileDirectoryTree.children) {
                files.push(file);
            }
        }
        objectNode.files = files;
        if (-1 <
            lodash_1.indexOf((_b = objectNode.entityCtx) === null || _b === void 0 ? void 0 : _b.implementedTypes, content_file_const_1.FILE_DIRECTORY_SELECTOR_TYPE.name) && ((_e = (_d = (_c = objectNode.entityCtx) === null || _c === void 0 ? void 0 : _c.jsonSchema) === null || _d === void 0 ? void 0 : _d.properties) === null || _e === void 0 ? void 0 : _e.selectedFiles)) {
            if (0 < files.length) {
                objectNode.entityCtx.jsonSchema.properties.selectedFiles.items.enumNames = [];
                objectNode.entityCtx.jsonSchema.properties.selectedFiles.items.enum = [];
                for (const file of files) {
                    if (-1 ===
                        lodash_1.indexOf(objectNode.entityCtx.jsonSchema.properties.selectedFiles.items
                            .enum, file.treeNode.name)) {
                        objectNode.entityCtx.jsonSchema.properties.selectedFiles.items.enum.push(file.treeNode.name);
                        objectNode.entityCtx.jsonSchema.properties.selectedFiles.items.enumNames.push(file.treeNode.name +
                            '<span class="fileSelect"><img onclick="showImg(\'' +
                            file.treeNode.contentFileUri +
                            '\')" src="' +
                            file.treeNode.contentFileUri +
                            '" ></span>');
                    }
                }
                if (objectNode.selectedFiles) {
                    objectNode.files = lodash_1.filter(files, (file) => -1 < lodash_1.indexOf(objectNode.selectedFiles, file.treeNode.name));
                }
                else {
                    objectNode.selectedFiles =
                        objectNode.entityCtx.jsonSchema.properties.selectedFiles.items.enum;
                }
                helper_1.addCondition("model.fileDirectoryObjectTreeId=='" +
                    objectNode.fileDirectoryObjectTreeId +
                    "'", objectNode.entityCtx.jsonSchema.properties.selectedFiles);
            }
            else {
                delete objectNode.entityCtx.jsonSchema.properties.selectedFiles;
            }
        }
        if (objectNode.fileDirectoryTree) {
            await this.addLoadFilesJsonSchemaMethod(objectNode, ctx);
        }
        else {
            await this.addCreateFilesDirectoryJsonSchemaMethod(objectNode, ctx);
        }
    }
};
TransientFileService = tslib_1.__decorate([
    tslib_1.__param(0, core_1.service(transient_entity_service_1.TransientEntityService)),
    tslib_1.__param(1, core_1.service(inside_rest_service_1.InsideRestService)),
    tslib_1.__param(2, core_1.service(uri_complete_service_1.UriCompleteService)),
    tslib_1.__param(3, core_1.service(content_file_definition_1.ContentFileService)),
    tslib_1.__param(4, core_1.service(services_1.ObjectTreeService)),
    tslib_1.__param(5, core_1.service(object_node_service_1.ObjectNodeService)),
    tslib_1.__param(6, core_1.service(object_type_service_1.ObjectTypeService)),
    tslib_1.__metadata("design:paramtypes", [transient_entity_service_1.TransientEntityService,
        inside_rest_service_1.InsideRestService,
        uri_complete_service_1.UriCompleteService,
        content_file_definition_1.ContentFileService,
        services_1.ObjectTreeService,
        object_node_service_1.ObjectNodeService,
        object_type_service_1.ObjectTypeService])
], TransientFileService);
exports.TransientFileService = TransientFileService;
//# sourceMappingURL=transient-file.service.js.map