"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContentFileService = void 0;
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/no-explicit-any */
const core_1 = require("@loopback/core");
const fs_1 = tslib_1.__importDefault(require("fs"));
const path_1 = tslib_1.__importDefault(require("path"));
const constants_1 = require("./../../constants");
const application_error_1 = require("./../../helper/application-error");
const content_entity_const_1 = require("./content-entity.const");
const content_entity_service_1 = require("./content-entity.service");
let ContentFileService = class ContentFileService {
    constructor(contentEntityService, storageDirectory) {
        this.contentEntityService = contentEntityService;
        this.storageDirectory = storageDirectory;
        this.providerId = content_entity_const_1.CONTENT_ENTITY_PROVIDER;
        this.serviceId = ContentFileService.name;
        this.contentEntityService.registerNewContentType('ContentFile', this);
    }
    getDirPath(entity) {
        return path_1.default.join(this.storageDirectory, './' + entity.entityName + '/' + entity.id);
    }
    getFilePath(entity, fieldName) {
        return path_1.default.join(this.getDirPath(entity), './' + fieldName);
    }
    async deleteContents(entities, fieldName = 'contentFile') {
        const contentIdsToDelete = entities.filter((entity) => {
            var _a;
            return (_a = entity[fieldName]) === null || _a === void 0 ? void 0 : _a.id;
        });
        for (const entity of contentIdsToDelete) {
            try {
                await fs_1.default.promises.unlink(this.getFilePath(entity, fieldName));
            }
            catch (error) { }
        }
    }
    async manageContent(entity, postedEntity, fieldName = 'contentFile') {
        var _a;
        const contentFileEntity = postedEntity[fieldName];
        if (!contentFileEntity ||
            !contentFileEntity.base64 ||
            !contentFileEntity.name) {
            if (((_a = entity[fieldName]) === null || _a === void 0 ? void 0 : _a.id) && !(contentFileEntity === null || contentFileEntity === void 0 ? void 0 : contentFileEntity.id)) {
                try {
                    await fs_1.default.promises.unlink(this.getFilePath(entity, fieldName));
                }
                catch (error) { }
                entity[fieldName] = {};
                return true;
            }
            return false;
        }
        const dirPath = this.getDirPath(entity);
        await fs_1.default.promises.mkdir(dirPath, { recursive: true });
        const filePath = this.getFilePath(entity, fieldName);
        await fs_1.default.promises.writeFile(filePath, Buffer.from(contentFileEntity.base64, 'base64'));
        entity[fieldName] = {
            name: contentFileEntity.name,
            id: contentFileEntity.name,
            size: contentFileEntity.size,
            type: contentFileEntity.type,
        };
        return true;
    }
    async getContentDefinition() {
        return {
            properties: {
                contentFile: {
                    type: 'file',
                    title: 'Single file',
                },
            },
        };
    }
    addTransientContent(entity) {
        return Promise.resolve();
    }
    async getContent(entity, fieldName, args) {
        var _a;
        if (((_a = entity === null || entity === void 0 ? void 0 : entity.contentFile) === null || _a === void 0 ? void 0 : _a.name) !== args.contentId) {
            throw application_error_1.ApplicationError.notFound({ file: args.contentId });
        }
        const dirPath = path_1.default.join(this.storageDirectory, './' + entity.entityName + '/' + entity.id);
        return {
            filePath: path_1.default.join(dirPath, './' + fieldName),
            fileName: entity.contentFile.name,
        };
    }
};
ContentFileService = tslib_1.__decorate([
    tslib_1.__param(0, core_1.service(content_entity_service_1.ContentEntityService)),
    tslib_1.__param(1, core_1.inject(constants_1.STORAGE_DIRECTORY)),
    tslib_1.__metadata("design:paramtypes", [content_entity_service_1.ContentEntityService, String])
], ContentFileService);
exports.ContentFileService = ContentFileService;
//# sourceMappingURL=content-file.service.js.map