"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 bfastnode_1 = require("bfastnode");
var sharp_1 = __importDefault(require("sharp"));
var filesAdapter;
var config;
var security;
var StorageController = (function () {
    function StorageController(files, securityController, configAdapter) {
        filesAdapter = files;
        security = securityController;
        config = configAdapter;
    }
    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, context) {
        return __awaiter(this, void 0, void 0, function () {
            var filename, base64, type, source, dataToSave, isBase64, file;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filename = fileModel.filename, base64 = fileModel.base64;
                        type = fileModel.type;
                        if (!filename) {
                            throw new Error('Filename required');
                        }
                        if (!base64) {
                            throw new Error('File base64 data to save is required');
                        }
                        if (!type) {
                            type = mime_1.default.getType(filename);
                        }
                        source = StorageController.getSource(base64, type);
                        dataToSave = {
                            data: source.base64,
                            filename: filename,
                            fileData: {
                                metadata: {},
                                tags: {},
                            },
                        };
                        if (source.type) {
                            dataToSave.type = source.type;
                        }
                        isBase64 = Buffer.from(dataToSave.data, 'base64').toString('base64') === dataToSave.data;
                        return [4, filesAdapter.createFile(dataToSave.filename, isBase64 === true ?
                                Buffer.from(dataToSave.data, 'base64')
                                : dataToSave.data, dataToSave === null || dataToSave === void 0 ? void 0 : dataToSave.type, {})];
                    case 1:
                        file = _a.sent();
                        return [2, filesAdapter.getFileLocation(file, config)];
                }
            });
        });
    };
    StorageController.prototype.isFileStreamable = function (req, filesController) {
        return (req.get('Range')
            && typeof filesController.handleFileStream === 'function'
            && filesController.canHandleFileStream === true);
    };
    StorageController.prototype.getFileData = function (request, response, thumbnail) {
        var _this = this;
        if (thumbnail === void 0) { thumbnail = false; }
        var filename = request.params.filename;
        var contentType = mime_1.default.getType(filename);
        if (thumbnail === true && contentType && contentType.toString().startsWith('image')) {
            filesAdapter.getFileData(filename, true).then(function (stream) {
                var width = parseInt(request.query.width ? request.query.width : 100);
                var height = parseInt(request.query.height ? request.query.height : 0);
                stream.pipe(sharp_1.default().resize(width, height !== 0 ? height : null)).pipe(response);
            }).catch(function (_) {
                _this._getFileData(filename, contentType, request, response);
            });
        }
        else {
            this._getFileData(filename, contentType, request, response);
        }
    };
    StorageController.prototype._getFileData = function (filename, contentType, request, response) {
        if (this.isFileStreamable(request, filesAdapter)) {
            filesAdapter
                .handleFileStream(filename, request, response, contentType)
                .catch(function () {
                response.status(404);
                response.set('Content-Type', 'text/plain');
                response.end('File not found.');
            });
        }
        else {
            filesAdapter
                .getFileData(filename, false)
                .then(function (data) {
                response.status(200);
                response.set('Content-Type', contentType);
                response.set('Content-Length', data.length);
                response.end(data);
            })
                .catch(function () {
                response.status(404);
                response.set('Content-Type', 'text/plain');
                response.end('File not found.');
            });
        }
    };
    StorageController.prototype.listFiles = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, filesAdapter.listFiles(data)];
            });
        });
    };
    StorageController.prototype.saveFromBuffer = function (fileModel, context) {
        return __awaiter(this, void 0, void 0, function () {
            var type, filename, data, newFilename, file;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        type = fileModel.type;
                        filename = fileModel.filename, data = fileModel.data;
                        if (!filename) {
                            throw new Error('Filename required');
                        }
                        if (!data) {
                            throw new Error('File base64 data to save is required');
                        }
                        if (!type) {
                            type = mime_1.default.getType(filename);
                        }
                        newFilename = (context && context.storage && context.storage.preserveName === true)
                            ? filename
                            : security.generateUUID() + '-' + filename;
                        return [4, filesAdapter.createFile(newFilename, data, type, {})];
                    case 1:
                        file = _a.sent();
                        return [2, filesAdapter.getFileLocation(file, config)];
                }
            });
        });
    };
    StorageController.prototype.delete = function (data, context) {
        return __awaiter(this, void 0, void 0, function () {
            var filename;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filename = data.filename;
                        if (!filename) {
                            throw new Error('Filename required');
                        }
                        return [4, filesAdapter.deleteFile(filename)];
                    case 1:
                        _a.sent();
                        return [2, filename];
                }
            });
        });
    };
    StorageController.prototype.isS3 = function () {
        return filesAdapter.isS3;
    };
    StorageController.prototype.handleGetFileBySignedUrl = function (request, response, thumbnail) {
        if (thumbnail === void 0) { thumbnail = false; }
        var filename = request.params.filename;
        var contentType = mime_1.default.getType(filename);
        filesAdapter.signedUrl(filename).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);
                bfastnode_1.bfast.init({ projectId: '', applicationId: '' });
                bfastnode_1.bfast.functions().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() });
        });
    };
    return StorageController;
}());
exports.StorageController = StorageController;
