"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StorageController = void 0;
var mime_1 = __importDefault(require("mime"));
var http_status_codes_1 = require("http-status-codes");
var bfast_1 = __importDefault(require("bfast"));
var sharp_1 = __importDefault(require("sharp"));
var buffer_1 = require("buffer");
var StorageController = (function () {
    function StorageController() {
    }
    StorageController.getSource = function (base64, type) {
        var data;
        var source;
        var dataUriRegexp = /^data:([a-zA-Z]+\/[-a-zA-Z0-9+.]+)(;charset=[a-zA-Z0-9\-\/]*)?;base64,/;
        var commaIndex = base64.indexOf(',');
        if (commaIndex !== -1) {
            var matches = dataUriRegexp.exec(base64.slice(0, commaIndex + 1));
            data = base64.slice(commaIndex + 1);
            source = {
                format: 'base64',
                base64: data,
                type: matches && matches.length > 0 ? matches[1] : type
            };
        }
        else {
            data = base64;
            source = {
                format: 'base64',
                base64: data,
                type: type
            };
        }
        return source;
    };
    StorageController.prototype.save = function (fileModel, _, filesAdapter, databaseAdapter, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var name, base64, type, source, dataToSave, isBase64, file;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        name = fileModel.name, base64 = fileModel.base64;
                        type = fileModel.type;
                        if (!name) {
                            throw new Error('Filename required');
                        }
                        if (!base64) {
                            throw new Error('File base64 data to save is required');
                        }
                        if (!type) {
                            type = mime_1.default.getType(name);
                        }
                        source = StorageController.getSource(base64, type);
                        dataToSave = {
                            data: source.base64,
                            name: name,
                            fileData: {
                                metadata: {},
                                tags: {},
                            },
                        };
                        if (source.type) {
                            dataToSave.type = source.type;
                        }
                        isBase64 = buffer_1.Buffer.from(dataToSave.data, 'base64').toString('base64') === dataToSave.data;
                        return [4, filesAdapter.createFile(dataToSave.name, (_a = dataToSave === null || dataToSave === void 0 ? void 0 : dataToSave.data) === null || _a === void 0 ? void 0 : _a.length, isBase64 === true ?
                                buffer_1.Buffer.from(dataToSave.data, 'base64')
                                : dataToSave.data, dataToSave === null || dataToSave === void 0 ? void 0 : dataToSave.type, databaseAdapter, options)];
                    case 1:
                        file = _b.sent();
                        return [2, filesAdapter.getFileLocation(file, options)];
                }
            });
        });
    };
    StorageController.prototype.checkStreamCapability = function (req, filesController) {
        return (req.get('Range')
            && typeof filesController.handleFileStream === 'function'
            && filesController.canHandleFileStream === true);
    };
    StorageController.prototype.handleGetFileRequest = function (request, response, thumbnail, databaseAdapter, filesAdapter, options) {
        var _this = this;
        var name = request.params.filename;
        var contentType = mime_1.default.getType(name);
        if (thumbnail === true && contentType && contentType.toString().startsWith('image')) {
            filesAdapter.getFileData(name, true, databaseAdapter, options).then(function (value) {
                var width = parseInt(request.query.width ? request.query.width.toString() : '100');
                var height = parseInt(request.query.height ? request.query.height.toString() : '0');
                value.data.pipe(sharp_1.default().resize(width, height !== 0 ? height : null)).pipe(response);
            }).catch(function (_) {
                _this.getFileData(name, contentType, request, response, databaseAdapter, filesAdapter, options);
            });
        }
        else {
            this.getFileData(name, contentType, request, response, databaseAdapter, filesAdapter, options);
        }
    };
    StorageController.prototype.getFileData = function (name, contentType, request, response, databaseAdapter, filesAdapter, options) {
        if (this.checkStreamCapability(request, filesAdapter)) {
            filesAdapter
                .handleFileStream(name, request, response, contentType, databaseAdapter, options)
                .catch(function (_43) {
                response.status(http_status_codes_1.StatusCodes.NOT_FOUND);
                response.json({ message: 'File not found' });
            });
        }
        else {
            filesAdapter
                .getFileData(name, false, databaseAdapter, options)
                .then(function (data) {
                response.status(http_status_codes_1.StatusCodes.OK);
                response.set({
                    'Content-Type': data.type,
                    'Content-Length': data.size
                });
                return response.send(data.data);
            })
                .catch(function (_12) {
                response.status(http_status_codes_1.StatusCodes.NOT_FOUND);
                response.json({ message: 'File not found' });
            });
        }
    };
    StorageController.prototype.listFiles = function (data, databaseAdapter, filesAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, filesAdapter.listFiles(data, databaseAdapter, options)];
            });
        });
    };
    StorageController.prototype.saveFromBuffer = function (fileModel, context, databaseAdapter, filesAdapter, securityController, options) {
        return __awaiter(this, void 0, void 0, function () {
            var type, name, data, size, newFilename, file;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        type = fileModel.type;
                        name = fileModel.name, data = fileModel.data, size = fileModel.size;
                        if (!size) {
                            throw new Error('File size required');
                        }
                        if (!name) {
                            throw new Error('Filename required');
                        }
                        if (!data) {
                            throw new Error('File base64 data to save is required');
                        }
                        if (!type) {
                            type = mime_1.default.getType(name);
                        }
                        newFilename = (context && context.storage && context.storage.preserveName === true)
                            ? name
                            : securityController.generateUUID() + '-' + name;
                        return [4, filesAdapter.createFile(newFilename, size, data, type, databaseAdapter, options)];
                    case 1:
                        file = _a.sent();
                        return [2, filesAdapter.getFileLocation(file, options)];
                }
            });
        });
    };
    StorageController.prototype.delete = function (data, _, databaseAdapter, filesAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            var name;
            return __generator(this, function (_a) {
                name = data.name;
                if (!name) {
                    throw new Error('Filename required');
                }
                return [2, filesAdapter.deleteFile(name, databaseAdapter, options)];
            });
        });
    };
    StorageController.prototype.isS3 = function (filesAdapter) {
        return filesAdapter.isS3;
    };
    StorageController.prototype.handleGetFileBySignedUrl = function (request, response, thumbnail, databaseAdapter, filesAdapter, options) {
        var name = request.params.filename;
        var contentType = mime_1.default.getType(name);
        filesAdapter.signedUrl(name, options).then(function (value) {
            if (thumbnail === true && contentType && contentType.toString().startsWith('image')) {
                var width_1 = parseInt(request.query.width ? request.query.width : 100);
                var height_1 = parseInt(request.query.height ? request.query.height : 0);
                bfast_1.default.init({ projectId: '_bfast_core_', applicationId: '_bfast_core_' }, '_bfast_core_');
                bfast_1.default.functions('_bfast_core_').request(value).get({
                    responseType: 'stream'
                }).then(function (value1) {
                    value1
                        .pipe(sharp_1.default().resize(width_1, height_1 !== 0 ? height_1 : null))
                        .pipe(response);
                }).catch(function (_) {
                    console.log(_);
                    response.redirect(value);
                });
            }
            else {
                response.redirect(value);
            }
        }).catch(function (reason) {
            response.status(http_status_codes_1.StatusCodes.EXPECTATION_FAILED).send({ message: reason && reason.message ? reason.message : reason.toString() });
        });
    };
    StorageController.prototype.fileInfo = function (request, response, databaseAdapter, filesAdapter, options) {
        var _a;
        filesAdapter
            .fileInfo((_a = request === null || request === void 0 ? void 0 : request.params) === null || _a === void 0 ? void 0 : _a.filename, databaseAdapter, options)
            .then(function (info) {
            response.status(200);
            response.set('Accept-Ranges', 'bytes');
            response.set('Content-Length', info.size.toString());
            response.end();
        })
            .catch(function (_23) {
            response.status(http_status_codes_1.StatusCodes.NOT_FOUND);
            response.json({ message: 'File not found' });
        });
    };
    return StorageController;
}());
exports.StorageController = StorageController;
