"use strict";
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 __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileController = void 0;
const api_1 = require("@hed-hog/api");
const api_locale_1 = require("@hed-hog/api-locale");
const api_pagination_1 = require("@hed-hog/api-pagination");
const common_1 = require("@nestjs/common");
const platform_express_1 = require("@nestjs/platform-express");
const fs_1 = require("fs");
const handlebars_1 = __importDefault(require("handlebars"));
const path_1 = require("path");
const delete_dto_1 = require("./dto/delete.dto");
const upload_dto_1 = require("./dto/upload.dto");
const file_service_1 = require("./file.service");
let FileController = class FileController {
    constructor(fileService) {
        this.fileService = fileService;
    }
    async list(paginationParams) {
        return this.fileService.getFiles(paginationParams);
    }
    async show(id) {
        return this.fileService.get(id);
    }
    async getTempOpenURL(id) {
        return {
            url: await this.fileService.tempOpenURL((await this.fileService.get(id)).path),
        };
    }
    async getTempURL(id, req) {
        const file = await this.fileService.get(id);
        const token = this.fileService.createDownloadToken(file.path, 3600);
        const origin = `${req.protocol}://${req.get('host')}`;
        return {
            url: `${origin}/file/download/${encodeURIComponent(token)}`,
        };
    }
    async download(token, res, locale) {
        try {
            const { stream, filename, mimetype, size } = await this.fileService.download(locale, token);
            const encodedFilename = encodeURIComponent(filename);
            res.set({
                'Content-Type': mimetype || 'application/octet-stream',
                'Content-Disposition': `attachment; filename="${filename}"; ` +
                    `filename*=UTF-8''${encodedFilename}`,
            });
            if (typeof size === 'number') {
                res.set('Content-Length', `${size}`);
            }
            stream.pipe(res);
            return;
        }
        catch (error) {
            // Buscar traduções
            const errorTitle = (0, api_locale_1.getLocaleText)('file.download.error_title', locale);
            const errorMessage = (0, api_locale_1.getLocaleText)('file.download.error_message', locale);
            const errorDetailsLabel = (0, api_locale_1.getLocaleText)('file.download.error_details', locale);
            const goBackText = (0, api_locale_1.getLocaleText)('file.download.go_back', locale);
            // Ler e compilar template
            const templatePath = (0, path_1.join)(__dirname, 'templates', 'download-error.html');
            const templateSource = (0, fs_1.readFileSync)(templatePath, 'utf-8');
            const template = handlebars_1.default.compile(templateSource);
            // Renderizar template com dados
            const html = template({
                locale: locale || 'en',
                errorTitle,
                errorMessage,
                errorDetailsLabel,
                errorDetails: (error === null || error === void 0 ? void 0 : error.message) || 'Unknown error occurred',
                goBackText,
            });
            res.status(400).set('Content-Type', 'text/html').send(html);
            return;
        }
    }
    async open(token, res, locale) {
        try {
            const numericId = Number(token);
            const isNumericId = Number.isInteger(numericId) && String(numericId) === token;
            if (isNumericId && numericId > 0) {
                const { stream, filename, mimetype, size } = await this.fileService.openById(locale, numericId);
                const encodedFilename = encodeURIComponent(filename);
                res.set({
                    'Content-Type': mimetype || 'application/octet-stream',
                    'Content-Disposition': `inline; filename="${filename}"; ` +
                        `filename*=UTF-8''${encodedFilename}`,
                });
                if (typeof size === 'number') {
                    res.set('Content-Length', `${size}`);
                }
                stream.pipe(res);
                return;
            }
            const { stream, filename, mimetype, size } = await this.fileService.download(locale, token);
            const encodedFilename = encodeURIComponent(filename);
            res.set({
                'Content-Type': mimetype || 'application/octet-stream',
                'Content-Disposition': `inline; filename="${filename}"; ` +
                    `filename*=UTF-8''${encodedFilename}`,
            });
            if (typeof size === 'number') {
                res.set('Content-Length', `${size}`);
            }
            stream.pipe(res);
            return;
        }
        catch (error) {
            const errorTitle = (0, api_locale_1.getLocaleText)('file.download.error_title', locale);
            const errorMessage = (0, api_locale_1.getLocaleText)('file.download.error_message', locale);
            const errorDetailsLabel = (0, api_locale_1.getLocaleText)('file.download.error_details', locale);
            const goBackText = (0, api_locale_1.getLocaleText)('file.download.go_back', locale);
            const templatePath = (0, path_1.join)(__dirname, 'templates', 'download-error.html');
            const templateSource = (0, fs_1.readFileSync)(templatePath, 'utf-8');
            const template = handlebars_1.default.compile(templateSource);
            const html = template({
                locale: locale || 'en',
                errorTitle,
                errorMessage,
                errorDetailsLabel,
                errorDetails: (error === null || error === void 0 ? void 0 : error.message) || 'Unknown error occurred',
                goBackText,
            });
            res.status(400).set('Content-Type', 'text/html').send(html);
            return;
        }
    }
    async upload(file, body) {
        const destination = body.destination || 'files';
        return this.fileService.upload(destination, file);
    }
    async delete(data, locale) {
        return this.fileService.delete(locale, data);
    }
};
exports.FileController = FileController;
__decorate([
    (0, common_1.Get)(),
    __param(0, (0, api_pagination_1.Pagination)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "list", null);
__decorate([
    (0, common_1.Get)(':id'),
    __param(0, (0, common_1.Param)('id', common_1.ParseIntPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "show", null);
__decorate([
    (0, common_1.Put)('open/:id'),
    __param(0, (0, common_1.Param)('id', common_1.ParseIntPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "getTempOpenURL", null);
__decorate([
    (0, common_1.Put)('download/:id'),
    __param(0, (0, common_1.Param)('id', common_1.ParseIntPipe)),
    __param(1, (0, common_1.Req)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number, Object]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "getTempURL", null);
__decorate([
    (0, api_1.Public)(),
    (0, common_1.Get)('download/:token'),
    __param(0, (0, common_1.Param)('token')),
    __param(1, (0, common_1.Res)()),
    __param(2, (0, api_locale_1.Locale)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "download", null);
__decorate([
    (0, api_1.Public)(),
    (0, common_1.Get)('open/:token'),
    __param(0, (0, common_1.Param)('token')),
    __param(1, (0, common_1.Res)()),
    __param(2, (0, api_locale_1.Locale)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object, String]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "open", null);
__decorate([
    (0, common_1.Post)(),
    (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)('file')),
    __param(0, (0, common_1.UploadedFile)()),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, upload_dto_1.UploadFileDTO]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "upload", null);
__decorate([
    (0, common_1.Delete)(),
    __param(0, (0, common_1.Body)()),
    __param(1, (0, api_locale_1.Locale)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [delete_dto_1.DeleteDTO, String]),
    __metadata("design:returntype", Promise)
], FileController.prototype, "delete", null);
exports.FileController = FileController = __decorate([
    (0, api_1.Role)(),
    (0, common_1.Controller)('file'),
    __param(0, (0, common_1.Inject)((0, common_1.forwardRef)(() => file_service_1.FileService))),
    __metadata("design:paramtypes", [file_service_1.FileService])
], FileController);
//# sourceMappingURL=file.controller.js.map