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());
    });
};
import * as block from 'multiformats/block';
import * as cbor from '@ipld/dag-cbor';
import { BlockstoreLevel } from './blockstore-level.js';
import { CID } from 'multiformats/cid';
import { createLevelDatabase } from './level-wrapper.js';
import { executeUnlessAborted } from '../utils/abort.js';
import { IndexLevel } from './index-level.js';
import { sha256 } from 'multiformats/hashes/sha2';
/**
 * A simple implementation of {@link MessageStore} that works in both the browser and server-side.
 * Leverages LevelDB under the hood.
 */
export 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 }, config);
        this.blockstore = new BlockstoreLevel({
            location: this.config.blockstoreLocation,
            createLevelDatabase: this.config.createLevelDatabase,
        });
        this.index = new 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 executeUnlessAborted(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal);
            const cid = CID.parse(cidString);
            const bytes = yield partition.get(cid, options);
            if (!bytes) {
                return undefined;
            }
            const decodedBlock = yield executeUnlessAborted(block.decode({ bytes, codec: cbor, hasher: 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 executeUnlessAborted(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal);
            const cid = CID.parse(cidString);
            yield partition.delete(cid, options);
            yield this.index.delete(cidString, options);
        });
    }
    put(tenant, message, 
    // indexes: Record<string, string>,
    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 executeUnlessAborted(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal);
            const encodedMessageBlock = yield executeUnlessAborted(block.encode({ value: message, codec: cbor, hasher: 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();
        });
    }
}
//# sourceMappingURL=message-store-level.js.map