"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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.RestController = void 0;
var http_status_codes_1 = __importStar(require("http-status-codes"));
var formidable_1 = __importDefault(require("formidable"));
var fs_1 = require("fs");
var util_1 = require("util");
var mime_1 = __importDefault(require("mime"));
var RestController = (function () {
    function RestController() {
    }
    RestController.prototype.getFile = function (request, response, _, storageController, databaseAdapter, filesAdapter, options) {
        var _a, _b;
        if (((_b = (_a = request === null || request === void 0 ? void 0 : request.method) === null || _a === void 0 ? void 0 : _a.toString()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'head') {
            storageController.fileInfo(request, response, databaseAdapter, filesAdapter, options);
        }
        else if (storageController.isS3(filesAdapter) === true) {
            storageController.handleGetFileBySignedUrl(request, response, false, databaseAdapter, filesAdapter, options);
        }
        else {
            storageController.handleGetFileRequest(request, response, false, databaseAdapter, filesAdapter, options);
        }
    };
    RestController.prototype.getThumbnail = function (request, response, _, storageController, databaseAdapter, filesAdapter, options) {
        if (storageController.isS3(filesAdapter) === true) {
            storageController.handleGetFileBySignedUrl(request, response, true, databaseAdapter, filesAdapter, options);
        }
        else {
            storageController.handleGetFileRequest(request, response, true, databaseAdapter, filesAdapter, options);
        }
    };
    RestController.prototype.getAllFiles = function (request, response, _, storageController, databaseAdapter, filesAdapter, options) {
        storageController.listFiles({
            skip: request.query.skip ? parseInt(request.query.skip.toString()) : 0,
            after: request.query.after.toString(),
            size: request.query.size ? parseInt(request.query.size.toString()) : 20,
            prefix: request.query.prefix ? request.query.prefix.toString() : '',
        }, databaseAdapter, filesAdapter, options).then(function (value) {
            response.json(value);
        }).catch(function (reason) {
            response.status(http_status_codes_1.StatusCodes.EXPECTATION_FAILED).send({ message: reason.toString() });
        });
    };
    RestController.prototype.multipartForm = function (request, response, _, storageController, securityController, databaseAdapter, filesAdapter, options) {
        var _this = this;
        var contentType = request.get('content-type').split(';')[0].toString().trim();
        if (contentType !== 'multipart/form-data'.trim()) {
            response.status(http_status_codes_1.StatusCodes.BAD_REQUEST).json({ message: 'Accept only multipart request' });
            return;
        }
        var form = formidable_1.default({
            multiples: true,
            maxFileSize: 10 * 1024 * 1024 * 1024,
            keepExtensions: true
        });
        form.parse(request, function (err, fields, files) { return __awaiter(_this, void 0, void 0, function () {
            var urls, _i, _a, file, fileMeta, regx, result, _b, _c, _d, _e, f_key, fileMeta, regx, result, e_1;
            var _f;
            var _g;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        _h.trys.push([0, 10, , 11]);
                        if (err) {
                            response.status(http_status_codes_1.StatusCodes.BAD_REQUEST).send(err.toString());
                            return [2];
                        }
                        urls = [];
                        if (request
                            && request.query
                            && request.query.pn
                            && request.query.pn.toString().trim().toLowerCase() === 'true') {
                            request.body.context.storage = { preserveName: true };
                        }
                        else {
                            request.body.context.storage = { preserveName: false };
                        }
                        _i = 0, _a = Object.values(files);
                        _h.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3, 5];
                        file = _a[_i];
                        fileMeta = { name: undefined, type: undefined };
                        regx = /[^0-9a-z.]/gi;
                        fileMeta.name = file.name ? file.name : 'noname'
                            .toString()
                            .replace(regx, '');
                        fileMeta.type = file.type;
                        _c = (_b = storageController).saveFromBuffer;
                        _f = {};
                        return [4, util_1.promisify(fs_1.readFile)(file.path)];
                    case 2: return [4, _c.apply(_b, [(_f.data = _h.sent(),
                                _f.type = fileMeta.type,
                                _f.size = file.size,
                                _f.name = fileMeta.name,
                                _f), request.body.context,
                            databaseAdapter,
                            filesAdapter,
                            securityController,
                            options])];
                    case 3:
                        result = _h.sent();
                        urls.push(result);
                        _h.label = 4;
                    case 4:
                        _i++;
                        return [3, 1];
                    case 5:
                        _d = 0, _e = Object.keys(fields);
                        _h.label = 6;
                    case 6:
                        if (!(_d < _e.length)) return [3, 9];
                        f_key = _e[_d];
                        fileMeta = { name: undefined, type: undefined };
                        regx = /[^0-9a-z.]/gi;
                        fileMeta.name = f_key
                            .toString()
                            .replace(regx, '');
                        fileMeta.type = mime_1.default.getType(f_key);
                        return [4, storageController.saveFromBuffer({
                                data: Buffer.from(fields[f_key]),
                                type: fileMeta.type,
                                size: (_g = fields[f_key]) === null || _g === void 0 ? void 0 : _g.length,
                                name: fileMeta.name
                            }, request.body.context, databaseAdapter, filesAdapter, securityController, options)];
                    case 7:
                        result = _h.sent();
                        urls.push(result);
                        _h.label = 8;
                    case 8:
                        _d++;
                        return [3, 6];
                    case 9:
                        response.status(http_status_codes_1.StatusCodes.OK).json({ urls: urls });
                        return [3, 11];
                    case 10:
                        e_1 = _h.sent();
                        console.log(e_1);
                        response.status(http_status_codes_1.StatusCodes.BAD_REQUEST).end(e_1.toString());
                        return [3, 11];
                    case 11: return [2];
                }
            });
        }); });
    };
    RestController.prototype.verifyApplicationId = function (request, response, next, options) {
        var applicationId = request.body.applicationId;
        if (applicationId === options.applicationId) {
            request.body.context = {
                applicationId: applicationId
            };
            next();
        }
        else {
            response.status(http_status_codes_1.default.UNAUTHORIZED).json({ message: 'unauthorized' });
        }
    };
    RestController.prototype.filePolicy = function (request, response, next, databaseController, securityController, databaseAdapter, authController, options) {
        authController.hasPermission(request.body.ruleId, databaseController, securityController, databaseAdapter, request.body.context, options).then(function (value) {
            if (value === true) {
                next();
            }
            else {
                throw { message: 'You can\'t access this file' };
            }
        }).catch(function (reason) {
            response.status(http_status_codes_1.StatusCodes.UNAUTHORIZED).send(reason);
        });
    };
    RestController.prototype.verifyToken = function (request, response, next, securityController, options) {
        var token = request.body.token;
        var headerToken = request.headers['x-bfast-token'];
        var masterKey = request.body.masterKey;
        if (masterKey === options.masterKey) {
            request.body.context.auth = true;
            request.body.context.uid = "masterKey";
            request.body.context.masterKey = masterKey;
            request.body.context.useMasterKey = true;
            next();
            return;
        }
        request.body.context.useMasterKey = false;
        var vToken = function () {
            securityController.verifyToken(token, options).then(function (value) {
                request.body.context.auth = true;
                request.body.context.uid = value.uid;
                next();
            }).catch(function (_) {
                request.body.context.auth = false;
                request.body.context.uid = null;
                next();
            });
        };
        if (token && token !== '') {
            vToken();
        }
        else if (headerToken && headerToken !== '') {
            vToken();
        }
        else {
            request.body.context.auth = false;
            request.body.context.uid = null;
            next();
        }
    };
    RestController.prototype.verifyMethod = function (request, response, next) {
        if (request.method === 'POST') {
            next();
        }
        else {
            response.status(403).json({ message: 'HTTP method not supported' });
        }
    };
    RestController.prototype.verifyBodyData = function (request, response, next) {
        var body = request.body;
        if (!body) {
            response.status(http_status_codes_1.default.BAD_REQUEST).json({ message: 'require non empty rule blocks request' });
        }
        else if (Object.keys(body).length === 0) {
            response.status(http_status_codes_1.default.BAD_REQUEST).json({ message: 'require non empty rule blocks request' });
        }
        else {
            delete body.context;
            next();
        }
    };
    RestController.prototype.handleRuleBlocks = function (request, response, _, rulesController, authController, updateRuleController, databaseController, securityController, storageController, authAdapter, databaseAdapter, filesAdapter, options) {
        var body = request.body;
        var results = { errors: {} };
        rulesController.handleAuthenticationRule(body, results, authController, databaseController, securityController, authAdapter, databaseAdapter, options).then(function (_1) {
            return rulesController.handleAuthorizationRule(body, results, authController, databaseController, securityController, databaseAdapter, options);
        }).then(function (_2) {
            return rulesController.handleCreateRules(body, results, authController, databaseController, securityController, databaseAdapter, options, null);
        }).then(function (_3) {
            return rulesController.handleUpdateRules(body, results, updateRuleController, authController, databaseController, securityController, databaseAdapter, options, null);
        }).then(function (_4) {
            return rulesController.handleDeleteRules(body, results, authController, databaseController, securityController, databaseAdapter, options, null);
        }).then(function (_5) {
            return rulesController.handleQueryRules(body, results, authController, databaseController, securityController, databaseAdapter, options, null);
        }).then(function (_6) {
            return rulesController.handleBulkRule(body, results, updateRuleController, authController, databaseController, securityController, databaseAdapter, options);
        }).then(function (_8) {
            return rulesController.handleStorageRule(body, results, storageController, authController, databaseController, securityController, authAdapter, databaseAdapter, filesAdapter, options);
        }).then(function (_9) {
            if (!(results.errors && Object.keys(results.errors).length > 0)) {
                delete results.errors;
            }
            response.status(http_status_codes_1.default.OK).json(results);
        }).catch(function (reason) {
            response.status(http_status_codes_1.default.EXPECTATION_FAILED).json({ message: reason.message ? reason.message : reason.toString() });
        });
    };
    return RestController;
}());
exports.RestController = RestController;
