"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var FileStorageProvider_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileStorageProvider = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const media_repository_1 = require("../../repository/media.repository");
const file_1 = require("../file");
const path = __importStar(require("path"));
const setting_service_1 = require("../setting.service");
const default_settings_provider_service_1 = require("../settings/default-settings-provider.service");
let FileStorageProvider = FileStorageProvider_1 = class FileStorageProvider {
    constructor(configService, fileService, mediaRepository, settingService) {
        this.configService = configService;
        this.fileService = fileService;
        this.mediaRepository = mediaRepository;
        this.settingService = settingService;
        this.logger = new common_1.Logger(FileStorageProvider_1.name);
    }
    async retrieve(entity, mediaFieldMetadata) {
        const media = await this.mediaRepository.findByEntityIdAndFieldIdAndModelMetadataId(entity.id, mediaFieldMetadata.id, mediaFieldMetadata.model.id, ['mediaStorageProviderMetadata']);
        for (const m of media) {
            m['_full_url'] = `${this.settingService.getConfigValue("baseUrl")}/${this.getFullFilePath(m.relativeUri)}`;
        }
        return media;
    }
    async store(files, entity, mediaFieldMetadata) {
        const result = [];
        for (const file of files) {
            const fileStoragePath = this.getFullFilePath(this.getFileName(file));
            await this.fileService.copy(file.path, fileStoragePath);
            await this.fileService.delete(file.path);
            const mediaEntity = await this.mediaRepository.createMedia({
                entityId: entity.id,
                modelMetadataId: mediaFieldMetadata.model.id,
                relativeUri: this.getFileName(file),
                mimeType: file.mimetype,
                fileSize: file.size,
                originalFileName: file.originalname,
                mediaStorageProviderMetadataId: mediaFieldMetadata.mediaStorageProvider.id,
                fieldMetadataId: mediaFieldMetadata.id
            });
            result.push(mediaEntity);
            this.logger.debug(`Stored media with`, mediaEntity);
        }
        ;
        return result;
    }
    async storeStreams(streamPairs, entity, mediaFieldMetadata) {
        const result = [];
        for (const pair of streamPairs) {
            const stream = pair[0];
            const fileName = pair[1];
            await this.fileService.writeStream(this.getFullFilePath(fileName), stream);
            const mediaEntity = await this.mediaRepository.createMedia({
                entityId: entity.id,
                modelMetadataId: mediaFieldMetadata.model.id,
                relativeUri: fileName,
                mediaStorageProviderMetadataId: mediaFieldMetadata.mediaStorageProvider.id,
                fieldMetadataId: mediaFieldMetadata.id
            });
            this.logger.debug(`Stored media with`, mediaEntity);
        }
        ;
        return result;
    }
    async delete(entity, mediaFieldMetadata) {
        const existingMedia = await this.mediaRepository.findByEntityIdAndFieldIdAndModelMetadataId(entity.id, mediaFieldMetadata.id, mediaFieldMetadata.model.id, ['mediaStorageProviderMetadata']);
        this.mediaRepository.deleteByEntityIdAndFieldIdAndModelMetadataId(entity.id, mediaFieldMetadata.id, mediaFieldMetadata.model.id);
        for (const media of existingMedia) {
            await this.fileService.delete(this.getFullFilePath(media.relativeUri));
        }
    }
    async deleteByMediaRecord(media) {
        if (!media?.relativeUri) {
            return;
        }
        await this.fileService.delete(this.getFullFilePath(media.relativeUri));
    }
    getFullFilePath(fileName) {
        const base = this.settingService.getConfigValue("fileStorageDir")
            || default_settings_provider_service_1.DEFAULT_MEDIA_FILE_STORAGE_DIR;
        if (path.isAbsolute(fileName) || fileName.startsWith(`${base}/`)) {
            return fileName;
        }
        return `${base}/${fileName}`;
    }
    getFileName(file) {
        return `${file.filename}-${file.originalname}`;
    }
};
exports.FileStorageProvider = FileStorageProvider;
exports.FileStorageProvider = FileStorageProvider = FileStorageProvider_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [config_1.ConfigService,
        file_1.DiskFileService,
        media_repository_1.MediaRepository,
        setting_service_1.SettingService])
], FileStorageProvider);
//# sourceMappingURL=file-storage-provider.js.map