"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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GridFsStorageFactory = void 0;
var mongodb_1 = require("mongodb");
var config;
var GridFsStorageFactory = (function () {
    function GridFsStorageFactory(configAdapter, mongoDatabaseURI, mongoOptions) {
        if (mongoOptions === void 0) { mongoOptions = {}; }
        this.mongoDatabaseURI = mongoDatabaseURI;
        this.mongoOptions = mongoOptions;
        this.canHandleFileStream = true;
        this.isS3 = false;
        config = configAdapter;
        if (!this.mongoDatabaseURI) {
            this.mongoDatabaseURI = config.mongoDbUri;
        }
        var defaultMongoOptions = {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        };
        this.mongoOptions = Object.assign(defaultMongoOptions, mongoOptions);
    }
    GridFsStorageFactory.prototype.connect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var client;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.connectionPromise) return [3, 2];
                        return [4, mongodb_1.MongoClient.connect(this.mongoDatabaseURI, this.mongoOptions)];
                    case 1:
                        client = _a.sent();
                        this.client = client;
                        this.connectionPromise = Promise.resolve(client.db());
                        return [2, client.db()];
                    case 2: return [2, this.connectionPromise];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.getBucket = function (bucket) {
        if (bucket === void 0) { bucket = 'fs'; }
        return __awaiter(this, void 0, void 0, function () {
            var database;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.connect()];
                    case 1:
                        database = _a.sent();
                        return [2, new mongodb_1.GridFSBucket(database, { bucketName: bucket })];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.createFile = function (filename, data, contentType, options) {
        if (options === void 0) { options = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var bucket;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.validateFilename(filename)];
                    case 1:
                        _a.sent();
                        return [4, this.getBucket()];
                    case 2:
                        bucket = _a.sent();
                        return [2, this._saveFile(filename, data, contentType, bucket, options)];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.deleteFile = function (filename) {
        return __awaiter(this, void 0, void 0, function () {
            var bucket, documents;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getBucket()];
                    case 1:
                        bucket = _a.sent();
                        return [4, bucket.find({ filename: filename }).toArray()];
                    case 2:
                        documents = _a.sent();
                        if (documents.length === 0) {
                            throw new Error('FileNotFound');
                        }
                        return [2, Promise.all(documents.map(function (doc) {
                                return bucket.delete(doc._id);
                            }))];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.getFileData = function (filename, asStream) {
        if (asStream === void 0) { asStream = false; }
        return __awaiter(this, void 0, void 0, function () {
            var bucket, files, stream;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getBucket('fs')];
                    case 1:
                        bucket = _a.sent();
                        return [4, bucket.find({ filename: filename }).toArray()];
                    case 2:
                        files = _a.sent();
                        if (files.length === 0) {
                            throw new Error('FileNotFound');
                        }
                        stream = bucket.openDownloadStreamByName(filename);
                        if (asStream === true) {
                            return [2, stream];
                        }
                        else {
                            stream.read();
                            return [2, new Promise(function (resolve, reject) {
                                    var chunks = [];
                                    stream.on('data', function (data) {
                                        chunks.push(data);
                                    });
                                    stream.on('end', function () {
                                        resolve(Buffer.concat(chunks));
                                    });
                                    stream.on('error', function (err) {
                                        reject(err);
                                    });
                                })];
                        }
                        return [2];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.getFileStream = function (filename) {
        return __awaiter(this, void 0, void 0, function () {
            var bucket;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getBucket('fs')];
                    case 1:
                        bucket = _a.sent();
                        return [2, bucket.openDownloadStreamByName(filename)];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.getFileLocation = function (filename, configAdapter) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, '/storage/' + configAdapter.applicationId + '/file/' + encodeURIComponent(filename)];
            });
        });
    };
    GridFsStorageFactory.prototype.getMetadata = function (filename) {
        return __awaiter(this, void 0, void 0, function () {
            var bucket, files, metadata;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getBucket()];
                    case 1:
                        bucket = _a.sent();
                        return [4, bucket.find({ filename: filename }).toArray()];
                    case 2:
                        files = _a.sent();
                        if (files.length === 0) {
                            return [2, {}];
                        }
                        metadata = files[0].metadata;
                        return [2, { metadata: metadata }];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.handleFileStream = function (filename, req, res, contentType) {
        return __awaiter(this, void 0, void 0, function () {
            var bucket, files, parts, partialstart, partialend, start, end, stream;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getBucket('fs')];
                    case 1:
                        bucket = _a.sent();
                        return [4, bucket.find({ filename: filename }).toArray()];
                    case 2:
                        files = _a.sent();
                        if (files.length === 0) {
                            throw new Error('FileNotFound');
                        }
                        parts = req.get('Range').replace(/bytes=/, '').split('-');
                        partialstart = parts[0];
                        partialend = parts[1];
                        start = parseInt(partialstart, 10);
                        end = partialend ? parseInt(partialend, 10) : files[0].length - 1;
                        res.writeHead(206, {
                            'Accept-Ranges': 'bytes',
                            'Content-Length': end - start + 1,
                            'Content-Range': 'bytes ' + start + '-' + end + '/' + files[0].length,
                            'Content-Type': contentType,
                        });
                        stream = bucket.openDownloadStreamByName(filename);
                        stream.start(start);
                        stream.on('data', function (chunk) {
                            res.write(chunk);
                        });
                        stream.on('error', function () {
                            res.sendStatus(404);
                        });
                        stream.on('end', function () {
                            res.end();
                        });
                        return [2];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.listFiles = function (query) {
        if (query === void 0) { query = {
            prefix: '',
            size: 20,
            skip: 0
        }; }
        return __awaiter(this, void 0, void 0, function () {
            var bucket;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.getBucket()];
                    case 1:
                        bucket = _a.sent();
                        return [2, bucket.find({
                                filename: {
                                    $regex: query.prefix, $options: 'i'
                                }
                            }, {
                                skip: query.skip,
                                limit: query.size,
                            }).toArray()];
                }
            });
        });
    };
    GridFsStorageFactory.prototype.validateFilename = function (filename) {
        if (filename.length > 128) {
            throw new Error('Filename too long.');
        }
        var regx = /^[_a-zA-Z0-9][a-zA-Z0-9@. ~_-]*$/;
        if (!filename.match(regx)) {
            throw new Error('Filename contains invalid characters.');
        }
        return null;
    };
    GridFsStorageFactory.prototype.signedUrl = function (filename) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, this.getFileLocation(filename, config)];
            });
        });
    };
    GridFsStorageFactory.prototype._saveFile = function (filename, data, contentType, bucket, options) {
        if (options === void 0) { options = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var stream;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, bucket.openUploadStream(filename, {
                            contentType: contentType,
                            metadata: options.metadata,
                        })];
                    case 1:
                        stream = _a.sent();
                        if (!data.pipe) return [3, 3];
                        return [4, data.pipe(stream)];
                    case 2:
                        _a.sent();
                        return [3, 5];
                    case 3: return [4, stream.write(data)];
                    case 4:
                        _a.sent();
                        stream.end();
                        _a.label = 5;
                    case 5: return [2, new Promise(function (resolve, reject) {
                            stream.on('finish', function () {
                                resolve(filename);
                            });
                            stream.on('error', reject);
                        })];
                }
            });
        });
    };
    return GridFsStorageFactory;
}());
exports.GridFsStorageFactory = GridFsStorageFactory;
