"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 };
    }
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IpfsFactory = void 0;
var ipfs_http_client_1 = require("ipfs-http-client");
var buffer_1 = require("buffer");
var debug_util_1 = require("../utils/debug.util");
var web3_storage_1 = require("web3.storage");
var it_to_stream_1 = __importDefault(require("it-to-stream"));
var uuid_1 = require("uuid");
var IpfsFactory = (function () {
    function IpfsFactory() {
    }
    IpfsFactory.prototype.ensureIpfs = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!IpfsFactory.ipfs) return [3, 2];
                        _a = IpfsFactory;
                        return [4, ipfs_http_client_1.create({
                                host: options.useLocalIpfs === true ? 'localhost' : 'ipfsnode'
                            })];
                    case 1:
                        _a.ipfs = _b.sent();
                        _b.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    IpfsFactory.prototype.generateCidFromData = function (data, buffer, domain, options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (options.useLocalIpfs) {
                    debug_util_1.devLog('use local ipfs');
                    return [2, this.generateCidFromLocalIpfsNode(buffer)];
                }
                else {
                    debug_util_1.devLog('use web3 ipfs');
                    return [2, this.generateCidFromWeb3IpfsNode(buffer, domain, data, options)];
                }
                return [2];
            });
        });
    };
    IpfsFactory.prototype.generateDataFromCid = function (cid, ipfsOptions, options) {
        var e_1, _a, e_2, _b;
        return __awaiter(this, void 0, void 0, function () {
            var results, data, results_1, results_1_1, chunk, e_1_1, buffer, results_2, results_2_1, chunk, e_2_1;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4, this.checkIfWeHaveCidInWeb3(cid, options)];
                    case 1:
                        if ((_c.sent()) === false) {
                            return [2, null];
                        }
                        debug_util_1.devLog('____start fetch cid content with jsipfs_______');
                        return [4, IpfsFactory.ipfs.cat(cid, {
                                offset: (ipfsOptions && ipfsOptions.json === false && ipfsOptions.start) ? ipfsOptions.start : undefined,
                                length: (ipfsOptions && ipfsOptions.json === false && ipfsOptions.end) ? ipfsOptions.end : undefined,
                                timeout: 1000 * 60 * 5,
                            })];
                    case 2:
                        results = _c.sent();
                        IpfsFactory.ipfs.pin.add(ipfs_http_client_1.CID.parse(cid)).catch(console.log);
                        debug_util_1.devLog('____cid content found with jsipfs______');
                        if (!((ipfsOptions === null || ipfsOptions === void 0 ? void 0 : ipfsOptions.json) === true)) return [3, 15];
                        data = '';
                        _c.label = 3;
                    case 3:
                        _c.trys.push([3, 8, 9, 14]);
                        results_1 = __asyncValues(results);
                        _c.label = 4;
                    case 4: return [4, results_1.next()];
                    case 5:
                        if (!(results_1_1 = _c.sent(), !results_1_1.done)) return [3, 7];
                        chunk = results_1_1.value;
                        data += chunk.toString();
                        _c.label = 6;
                    case 6: return [3, 4];
                    case 7: return [3, 14];
                    case 8:
                        e_1_1 = _c.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 14];
                    case 9:
                        _c.trys.push([9, , 12, 13]);
                        if (!(results_1_1 && !results_1_1.done && (_a = results_1.return))) return [3, 11];
                        return [4, _a.call(results_1)];
                    case 10:
                        _c.sent();
                        _c.label = 11;
                    case 11: return [3, 13];
                    case 12:
                        if (e_1) throw e_1.error;
                        return [7];
                    case 13: return [7];
                    case 14: return [2, JSON.parse(data)];
                    case 15:
                        if (!((ipfsOptions === null || ipfsOptions === void 0 ? void 0 : ipfsOptions.json) === false)) return [3, 29];
                        if (!((ipfsOptions === null || ipfsOptions === void 0 ? void 0 : ipfsOptions.stream) === true)) return [3, 16];
                        return [2, it_to_stream_1.default.readable(results)];
                    case 16:
                        buffer = buffer_1.Buffer.alloc(0);
                        _c.label = 17;
                    case 17:
                        _c.trys.push([17, 22, 23, 28]);
                        results_2 = __asyncValues(results);
                        _c.label = 18;
                    case 18: return [4, results_2.next()];
                    case 19:
                        if (!(results_2_1 = _c.sent(), !results_2_1.done)) return [3, 21];
                        chunk = results_2_1.value;
                        buffer = buffer_1.Buffer.concat([buffer, chunk]);
                        _c.label = 20;
                    case 20: return [3, 18];
                    case 21: return [3, 28];
                    case 22:
                        e_2_1 = _c.sent();
                        e_2 = { error: e_2_1 };
                        return [3, 28];
                    case 23:
                        _c.trys.push([23, , 26, 27]);
                        if (!(results_2_1 && !results_2_1.done && (_b = results_2.return))) return [3, 25];
                        return [4, _b.call(results_2)];
                    case 24:
                        _c.sent();
                        _c.label = 25;
                    case 25: return [3, 27];
                    case 26:
                        if (e_2) throw e_2.error;
                        return [7];
                    case 27: return [7];
                    case 28: return [2, buffer];
                    case 29: return [2];
                }
            });
        });
    };
    IpfsFactory.prototype.generateCidFromLocalIpfsNode = function (buffer) {
        return __awaiter(this, void 0, void 0, function () {
            var r;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, IpfsFactory.ipfs.add(buffer, {
                            wrapWithDirectory: false
                        })];
                    case 1:
                        r = _a.sent();
                        debug_util_1.devLog('done save file to local ipfs with cid', r.cid.toString());
                        return [2, {
                                cid: r.cid.toString(),
                                size: r.size
                            }];
                }
            });
        });
    };
    IpfsFactory.prototype.generateCidFromWeb3IpfsNode = function (buffer, domain, data, options) {
        return __awaiter(this, void 0, void 0, function () {
            var web3Storage, file, r;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        web3Storage = new web3_storage_1.Web3Storage({
                            token: options.web3Token
                        });
                        file = new web3_storage_1.File([buffer], domain + "_" + data._id);
                        return [4, web3Storage.put([file], {
                                wrapWithDirectory: false,
                                name: domain + "_" + uuid_1.v4(),
                            })];
                    case 1:
                        r = _a.sent();
                        return [2, {
                                cid: r,
                                size: 0
                            }];
                }
            });
        });
    };
    IpfsFactory.prototype.checkIfWeHaveCidInWeb3 = function (cid, options) {
        return __awaiter(this, void 0, void 0, function () {
            var web3Storage, data, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(options.useLocalIpfs === true)) return [3, 1];
                        return [2, true];
                    case 1:
                        web3Storage = new web3_storage_1.Web3Storage({
                            token: options.web3Token
                        });
                        return [4, web3Storage.get(cid)];
                    case 2:
                        data = _b.sent();
                        _a = data.ok;
                        if (!_a) return [3, 4];
                        return [4, data.files];
                    case 3:
                        _a = (_b.sent());
                        _b.label = 4;
                    case 4: return [2, !!(_a)];
                }
            });
        });
    };
    return IpfsFactory;
}());
exports.IpfsFactory = IpfsFactory;
