"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.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.filesRouter = void 0;
var gridfs_stream_1 = __importDefault(require("gridfs-stream"));
var mongoose_1 = __importDefault(require("mongoose"));
var multer_1 = __importDefault(require("multer"));
var multer_gridfs_storage_1 = __importDefault(require("multer-gridfs-storage"));
var path = __importStar(require("path"));
var config_1 = __importDefault(require("~/config"));
var routes_1 = require("~/core/routes");
var auth_1 = require("~/modules/auth");
var services_1 = require("../services");
var privateRouter = routes_1.createRouter();
var gfs;
var connectionString = config_1.default.db.connectionString.replace('%PASSWORD%', config_1.default.db.password);
var conn = mongoose_1.default.createConnection(connectionString, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
conn.once('open', function () {
    gfs = gridfs_stream_1.default(conn.db, mongoose_1.default.mongo);
    gfs.collection('fs');
});
var storage = new multer_gridfs_storage_1.default({
    url: connectionString,
    file: function (req, file) { return ({
        filename: path.resolve(req.query.path, file.originalname)
    }); }
});
var upload = multer_1.default({ storage: storage });
privateRouter.post('/upload', auth_1.authenticate, upload.array('files'), function (req, res) {
    res.sendStatus(200);
});
privateRouter.get('/files-folders', auth_1.authenticate, routes_1.catchAsync(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
    var _a, _b, _c, _d, _e;
    return __generator(this, function (_f) {
        switch (_f.label) {
            case 0:
                _b = (_a = res).json;
                _d = (_c = services_1.filesService).getFilesAndFolders;
                _e = [req.query.path];
                return [4 /*yield*/, conn];
            case 1: return [4 /*yield*/, _d.apply(_c, _e.concat([_f.sent()]))];
            case 2:
                _b.apply(_a, [_f.sent()]);
                return [2 /*return*/];
        }
    });
}); }));
privateRouter.post('/update-filename', auth_1.authenticate, routes_1.catchAsync(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
    var _a, _b, _c;
    return __generator(this, function (_d) {
        switch (_d.label) {
            case 0:
                _b = (_a = services_1.filesService).updateFilename;
                _c = [req.body];
                return [4 /*yield*/, conn];
            case 1: return [4 /*yield*/, _b.apply(_a, _c.concat([_d.sent()]))];
            case 2:
                _d.sent();
                res.sendStatus(200);
                return [2 /*return*/];
        }
    });
}); }));
var staticRouter = routes_1.createRouter();
staticRouter.get('*', routes_1.catchAsync(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
    var filename;
    return __generator(this, function (_a) {
        filename = req.params[0];
        gfs.exist({ filename: filename }, function (err, found) { return __awaiter(void 0, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (err || !found) {
                    return [2 /*return*/, res.status(404).send('File not found')];
                }
                gfs.files.find({ filename: filename }).toArray(function (_, files) {
                    res.set('Content-Type', files[0].contentType);
                    res.set('Content-Disposition', 'attachment; filename="' + files[0].filename + '"');
                    var readstream = gfs.createReadStream({ filename: filename });
                    readstream.pipe(res);
                });
                return [2 /*return*/];
            });
        }); });
        return [2 /*return*/];
    });
}); }));
exports.filesRouter = routes_1.createRouter();
exports.filesRouter.use('/files', privateRouter);
exports.filesRouter.use('/static', staticRouter);
