"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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.IpfsStorageFactory = void 0;
var stream_1 = require("stream");
var ipfs_factory_1 = require("./ipfs.factory");
var IpfsStorageFactory = (function () {
    function IpfsStorageFactory() {
        this.domain = '_Storage';
        this.ipfsFactory = new ipfs_factory_1.IpfsFactory();
        this.canHandleFileStream = true;
        this.isS3 = false;
    }
    IpfsStorageFactory.prototype.createFile = function (name, size, data, contentType, databaseAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.validateFilename(name)];
                    case 1:
                        _a.sent();
                        return [2, this._saveFile(name, size, data, contentType, databaseAdapter, options)];
                }
            });
        });
    };
    IpfsStorageFactory.prototype.deleteFile = function (name, databaseAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            var r;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, databaseAdapter.delete(this.domain, IpfsStorageFactory.sanitize4Saving({ _id: name, id: name }), {}, options)];
                    case 1:
                        r = _a.sent();
                        return [2, r.map(function (x) { return IpfsStorageFactory.sanitize4User(x); })];
                }
            });
        });
    };
    IpfsStorageFactory.prototype.fileInfo = function (name, databaseAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            var fObj, file;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        fObj = IpfsStorageFactory.sanitize4Saving({
                            _id: name
                        });
                        return [4, databaseAdapter.findOne(this.domain, {
                                _id: fObj._id,
                                return: []
                            }, {}, options)];
                    case 1:
                        file = _a.sent();
                        if (file && file.size && file.name) {
                            return [2, file];
                        }
                        else {
                            throw { message: 'File info can not be determined' };
                        }
                        return [2];
                }
            });
        });
    };
    IpfsStorageFactory.prototype.getFileData = function (name, asStream, databaseAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            var fObj, file, data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        fObj = IpfsStorageFactory.sanitize4Saving({
                            _id: name
                        });
                        return [4, databaseAdapter.findOne(this.domain, {
                                _id: fObj._id,
                                return: []
                            }, {}, options)];
                    case 1:
                        file = _a.sent();
                        file = IpfsStorageFactory.sanitize4User(file);
                        if (!(file && file.cid)) return [3, 3];
                        return [4, this.ipfsFactory.generateDataFromCid(file.cid, {
                                json: false,
                                stream: asStream
                            }, options)];
                    case 2:
                        data = _a.sent();
                        return [2, __assign({ data: data }, file)];
                    case 3: throw 'file not found, maybe its deleted';
                }
            });
        });
    };
    IpfsStorageFactory.prototype.getFileLocation = function (name, configAdapter) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, '/storage/' + configAdapter.applicationId + '/file/' + encodeURIComponent(name)];
            });
        });
    };
    IpfsStorageFactory.prototype.handleFileStream = function (name, req, res, contentType, databaseAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            var fObj, file, size, range, parts, start, end, buffer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        fObj = IpfsStorageFactory.sanitize4Saving({
                            _id: name
                        });
                        return [4, databaseAdapter.findOne(this.domain, {
                                _id: fObj._id,
                                return: []
                            }, {}, options)];
                    case 1:
                        file = _a.sent();
                        if (!(file && file.cid && file.type && file.size)) return [3, 3];
                        size = file.size;
                        range = req.headers.range;
                        parts = range.replace(/bytes=/, "").split('-');
                        start = parts[0];
                        end = parts[1];
                        start = parseInt(start, 10);
                        end = end ? parseInt(end, 10) : size - 1;
                        if (!isNaN(start) && isNaN(end)) {
                            end = size - 1;
                        }
                        if (isNaN(start) && !isNaN(end)) {
                            start = size - end;
                            end = size - 1;
                        }
                        if (start >= size || end >= size) {
                            res.writeHead(416, {
                                "Content-Range": "bytes */" + size
                            });
                            return [2, res.end()];
                        }
                        res.writeHead(206, {
                            "Content-Range": "bytes " + start + "-" + end + "/" + size,
                            "Accept-Ranges": "bytes",
                            "Content-Length": "" + (end - start + 1),
                            "Content-Type": file.type
                        });
                        return [4, this.ipfsFactory.generateDataFromCid(file.cid, {
                                json: false,
                                stream: true,
                                start: start,
                                end: end
                            }, options)];
                    case 2:
                        buffer = _a.sent();
                        stream_1.pipeline(buffer, res, function (err) {
                            if (err) {
                                try {
                                    res.end();
                                }
                                catch (_) {
                                }
                            }
                        });
                        return [3, 4];
                    case 3: throw 'file not found, maybe its deleted';
                    case 4: return [2];
                }
            });
        });
    };
    IpfsStorageFactory.prototype.listFiles = function (query, databaseAdapter, options) {
        if (query === void 0) { query = {
            prefix: '',
            size: 20,
            skip: 0
        }; }
        return __awaiter(this, void 0, void 0, function () {
            var r;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, databaseAdapter.findMany(this.domain, {
                            filter: {},
                            return: [],
                            size: query.size,
                            skip: query.skip
                        }, {}, options)];
                    case 1:
                        r = _a.sent();
                        if (Array.isArray(r)) {
                            r = r.filter(function (x) { var _a, _b; return (_b = (_a = x === null || x === void 0 ? void 0 : x.name) === null || _a === void 0 ? void 0 : _a.toString()) === null || _b === void 0 ? void 0 : _b.includes(query.prefix); }).map(function (x) { return IpfsStorageFactory.sanitize4User(x); });
                            return [2, r];
                        }
                        else {
                            return [2, []];
                        }
                        return [2];
                }
            });
        });
    };
    IpfsStorageFactory.prototype.validateFilename = function (name) {
        if (name.length > 128) {
            throw new Error('name too long.');
        }
        var regx = /^[_a-zA-Z0-9][a-zA-Z0-9@. ~_-]*$/;
        if (!name.match(regx)) {
            throw new Error('Filename contains invalid characters.');
        }
        return null;
    };
    IpfsStorageFactory.prototype.signedUrl = function (name, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2, this.getFileLocation(name, options)];
            });
        });
    };
    IpfsStorageFactory.prototype._saveFile = function (name, size, data, contentType, databaseAdapter, options) {
        return __awaiter(this, void 0, void 0, function () {
            var _obj, dataRes, _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _obj = IpfsStorageFactory.sanitize4Saving({
                            _id: name,
                            name: name,
                            type: contentType,
                            cid: null
                        });
                        return [4, this.ipfsFactory.generateCidFromData(_obj, data, this.domain, options)];
                    case 1:
                        dataRes = _c.sent();
                        _obj.cid = dataRes.cid;
                        _obj.size = size;
                        _b = (_a = IpfsStorageFactory).sanitize4User;
                        return [4, databaseAdapter.writeOne(this.domain, _obj, {}, options)];
                    case 2:
                        _b.apply(_a, [_c.sent()]);
                        return [2, name];
                }
            });
        });
    };
    IpfsStorageFactory.sanitize4Saving = function (data) {
        var _a, _b, _c, _d, _e;
        if (data && JSON.stringify(data).startsWith('{')) {
            data._id = (_b = (_a = data === null || data === void 0 ? void 0 : data._id) === null || _a === void 0 ? void 0 : _a.replace('.', '%')) === null || _b === void 0 ? void 0 : _b.concat('-id');
            data.id = (_d = (_c = data === null || data === void 0 ? void 0 : data.id) === null || _c === void 0 ? void 0 : _c.replace('.', '%')) === null || _d === void 0 ? void 0 : _d.concat('-id');
            data.name = (_e = data === null || data === void 0 ? void 0 : data.name) === null || _e === void 0 ? void 0 : _e.replace('.', '%');
        }
        return data;
    };
    IpfsStorageFactory.sanitize4User = function (x) {
        var _a, _b, _c;
        if (x && JSON.stringify(x).startsWith('{')) {
            x._id = (_b = (_a = x === null || x === void 0 ? void 0 : x._id) === null || _a === void 0 ? void 0 : _a.replace(new RegExp('%', 'ig'), '.')) === null || _b === void 0 ? void 0 : _b.replace(new RegExp('-id', 'ig'), '');
            x.name = (_c = x === null || x === void 0 ? void 0 : x.name) === null || _c === void 0 ? void 0 : _c.replace(new RegExp('%', 'ig'), '.');
        }
        return x;
    };
    IpfsStorageFactory.prototype.init = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.ipfsFactory.ensureIpfs(options)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    return IpfsStorageFactory;
}());
exports.IpfsStorageFactory = IpfsStorageFactory;
