"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageStoreLevel = void 0;
const block = __importStar(require("multiformats/block"));
const cbor = __importStar(require("@ipld/dag-cbor"));
const blockstore_level_js_1 = require("./blockstore-level.js");
const cid_1 = require("multiformats/cid");
const level_wrapper_js_1 = require("./level-wrapper.js");
const abort_js_1 = require("../utils/abort.js");
const index_level_js_1 = require("./index-level.js");
const sha2_1 = require("multiformats/hashes/sha2");
/**
 * A simple implementation of {@link MessageStore} that works in both the browser and server-side.
 * Leverages LevelDB under the hood.
 */
class MessageStoreLevel {
    /**
     * @param {MessageStoreLevelConfig} config
     * @param {string} config.blockstoreLocation - must be a directory path (relative or absolute) where
     *  LevelDB will store its files, or in browsers, the name of the
     * {@link https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase IDBDatabase} to be opened.
     * @param {string} config.indexLocation - same as config.blockstoreLocation
     */
    constructor(config = {}) {
        this.config = Object.assign({ blockstoreLocation: 'data/MESSAGESTORE', indexLocation: 'data/INDEX', createLevelDatabase: level_wrapper_js_1.createLevelDatabase }, config);
        this.blockstore = new blockstore_level_js_1.BlockstoreLevel({
            location: this.config.blockstoreLocation,
            createLevelDatabase: this.config.createLevelDatabase,
        });
        this.index = new index_level_js_1.IndexLevel({
            location: this.config.indexLocation,
            createLevelDatabase: this.config.createLevelDatabase,
        });
    }
    open() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.blockstore.open();
            yield this.index.open();
        });
    }
    close() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.blockstore.close();
            yield this.index.close();
        });
    }
    get(tenant, cidString, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
            const partition = yield (0, abort_js_1.executeUnlessAborted)(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal);
            const cid = cid_1.CID.parse(cidString);
            const bytes = yield partition.get(cid, options);
            if (!bytes) {
                return undefined;
            }
            const decodedBlock = yield (0, abort_js_1.executeUnlessAborted)(block.decode({ bytes, codec: cbor, hasher: sha2_1.sha256 }), options === null || options === void 0 ? void 0 : options.signal);
            const message = decodedBlock.value;
            return message;
        });
    }
    query(tenant, filter, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
            const messages = [];
            const resultIds = yield this.index.query(Object.assign(Object.assign({}, filter), { tenant }), options);
            for (const id of resultIds) {
                const message = yield this.get(tenant, id, options);
                if (message) {
                    messages.push(message);
                }
            }
            return messages;
        });
    }
    delete(tenant, cidString, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
            const partition = yield (0, abort_js_1.executeUnlessAborted)(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal);
            const cid = cid_1.CID.parse(cidString);
            yield partition.delete(cid, options);
            yield this.index.delete(cidString, options);
        });
    }
    put(tenant, message, indexes, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted();
            const partition = yield (0, abort_js_1.executeUnlessAborted)(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal);
            const encodedMessageBlock = yield (0, abort_js_1.executeUnlessAborted)(block.encode({ value: message, codec: cbor, hasher: sha2_1.sha256 }), options === null || options === void 0 ? void 0 : options.signal);
            yield partition.put(encodedMessageBlock.cid, encodedMessageBlock.bytes, options);
            const encodedMessageBlockCid = encodedMessageBlock.cid.toString();
            const indexDocument = Object.assign(Object.assign({}, indexes), { tenant });
            yield this.index.put(encodedMessageBlockCid, indexDocument, options);
        });
    }
    /**
     * deletes everything in the underlying blockstore and indices.
     */
    clear() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.blockstore.clear();
            yield this.index.clear();
        });
    }
    dump() {
        var _a, _b, _c, _d;
        return __awaiter(this, void 0, void 0, function* () {
            console.group('blockstore');
            yield ((_b = (_a = this.blockstore)['dump']) === null || _b === void 0 ? void 0 : _b.call(_a));
            console.groupEnd();
            console.group('index');
            yield ((_d = (_c = this.index)['dump']) === null || _d === void 0 ? void 0 : _d.call(_c));
            console.groupEnd();
        });
    }
}
exports.MessageStoreLevel = MessageStoreLevel;
//# sourceMappingURL=message-store-level.js.map