"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 rules_controller_1 = require("./rules.controller");
var update_rule_controller_1 = require("./update.rule.controller");
var stream_1 = require("stream");
var formidable_1 = __importDefault(require("formidable"));
var log_controller_1 = require("./log.controller");
var restSecurity;
var restAuthController;
var restStorageController;
var restConfig;
var RestController = (function () {
    function RestController(_restSecurity, _restAuthController, _restStorageController, _restConfig) {
        restSecurity = _restSecurity;
        restAuthController = _restAuthController;
        restStorageController = _restStorageController;
        restConfig = _restConfig;
    }
    RestController.prototype.getFile = function (request, response, _) {
        if (restStorageController.isS3() === true) {
            restStorageController.handleGetFileBySignedUrl(request, response, !!request.query.thumbnail);
            return;
        }
        else {
            restStorageController.getFileData(request, response, false);
            return;
        }
    };
    RestController.prototype.getThumbnail = function (request, response, _) {
        if (restStorageController.isS3() === true) {
            restStorageController.handleGetFileBySignedUrl(request, response, true);
            return;
        }
        else {
            restStorageController.getFileData(request, response, true);
            return;
        }
    };
    RestController.prototype.getAllFiles = function (request, response, _) {
        restStorageController.listFiles({
            skip: request.query.skip ? request.query.skip : 0,
            after: request.query.after,
            size: request.query.size ? request.query.size : 20,
            prefix: request.query.prefix ? request.query.prefix : '',
        }).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, _) {
        var _this = this;
        var form = formidable_1.default({
            multiples: true,
            maxFileSize: 10 * 1024 * 1024 * 1024,
            keepExtensions: true
        });
        var passThrough = new stream_1.PassThrough();
        var fileMeta = { name: undefined, type: undefined };
        form.onPart = function (part) {
            if (!part.filename) {
                form.handlePart(part);
                return;
            }
            var regx = /[^0-9a-z.]/gi;
            fileMeta.name = part.filename
                .toString()
                .replace(regx, '');
            fileMeta.type = part.mime;
            part.on('data', function (buffer) {
                passThrough.write(buffer);
            });
            part.on('end', function () {
                passThrough.end();
            });
        };
        form.parse(request, function (err, _0, _1) { return __awaiter(_this, void 0, void 0, function () {
            var urls, result, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        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() === 'true') {
                            request.body.context.storage = { preserveName: true };
                        }
                        else {
                            request.body.context.storage = { preserveName: false };
                        }
                        return [4, restStorageController.saveFromBuffer({
                                data: passThrough,
                                type: fileMeta.type,
                                filename: fileMeta.name
                            }, request.body.context)];
                    case 1:
                        result = _a.sent();
                        urls.push(result);
                        response.status(http_status_codes_1.StatusCodes.OK).json({ urls: urls });
                        return [3, 3];
                    case 2:
                        e_1 = _a.sent();
                        console.log(e_1);
                        response.status(http_status_codes_1.StatusCodes.BAD_REQUEST).end(e_1.toString());
                        return [3, 3];
                    case 3: return [2];
                }
            });
        }); });
        return;
    };
    RestController.prototype.verifyApplicationId = function (request, response, next) {
        var applicationId = request.body.applicationId;
        if (applicationId === restConfig.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) {
        restAuthController.hasPermission(request.body.ruleId, request.body.context).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) {
        var token = request.body.token;
        var headerToken = request.headers['x-bfast-token'];
        var masterKey = request.body.masterKey;
        if (masterKey === restConfig.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;
        if (token && token !== '') {
            restSecurity.verifyToken(token).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();
            });
        }
        else if (headerToken && headerToken !== '') {
            restSecurity.verifyToken(headerToken).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();
            });
        }
        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, _) {
        var body = request.body;
        var results = { errors: {} };
        var rulesController = new rules_controller_1.RulesController(new update_rule_controller_1.UpdateRuleController(), new log_controller_1.LogController(restConfig), restConfig);
        rulesController.handleIndexesRule(body, results).then(function (__) {
            return rulesController.handleAuthenticationRule(body, results);
        }).then(function (_1) {
            return rulesController.handleAuthorizationRule(body, results);
        }).then(function (_2) {
            return rulesController.handleCreateRules(body, results);
        }).then(function (_3) {
            return rulesController.handleUpdateRules(body, results);
        }).then(function (_4) {
            return rulesController.handleDeleteRules(body, results);
        }).then(function (_5) {
            return rulesController.handleQueryRules(body, results);
        }).then(function (_6) {
            return rulesController.handleTransactionRule(body, results);
        }).then(function (_7) {
            return rulesController.handleAggregationRules(body, results);
        }).then(function (_8) {
            return rulesController.handleStorageRule(body, results);
        }).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;
