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 __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); }
};
import { monotonicFactory } from 'ulid';
import { createLevelDatabase, LevelWrapper } from '../store/level-wrapper.js';
const WATERMARKS_SUBLEVEL_NAME = 'watermarks';
const CIDS_SUBLEVEL_NAME = 'cids';
export class EventLogLevel {
    constructor(config) {
        this.config = Object.assign({ location: 'data/EVENTLOG', createLevelDatabase }, config);
        this.db = new LevelWrapper(Object.assign(Object.assign({}, this.config), { valueEncoding: 'utf8' }));
        this.ulid = monotonicFactory();
    }
    open() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.db.open();
        });
    }
    close() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.db.close();
        });
    }
    clear() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.db.clear();
        });
    }
    append(tenant, messageCid) {
        return __awaiter(this, void 0, void 0, function* () {
            const tenantEventLog = yield this.db.partition(tenant);
            const watermarkLog = yield tenantEventLog.partition(WATERMARKS_SUBLEVEL_NAME);
            const cidLog = yield tenantEventLog.partition(CIDS_SUBLEVEL_NAME);
            const watermark = this.ulid();
            yield watermarkLog.put(watermark, messageCid);
            yield cidLog.put(messageCid, watermark);
            return watermark;
        });
    }
    getEvents(tenant, options) {
        var e_1, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const tenantEventLog = yield this.db.partition(tenant);
            const watermarkLog = yield tenantEventLog.partition(WATERMARKS_SUBLEVEL_NAME);
            const events = [];
            try {
                for (var _b = __asyncValues(watermarkLog.iterator(options)), _c; _c = yield _b.next(), !_c.done;) {
                    const [key, value] = _c.value;
                    const event = { watermark: key, messageCid: value };
                    events.push(event);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return events;
        });
    }
    deleteEventsByCid(tenant, cids) {
        return __awaiter(this, void 0, void 0, function* () {
            if (cids.length === 0) {
                return 0;
            }
            const tenantEventLog = yield this.db.partition(tenant);
            const cidLog = yield tenantEventLog.partition(CIDS_SUBLEVEL_NAME);
            let ops = [];
            const promises = [];
            for (const cid of cids) {
                ops.push({ type: 'del', key: cid });
                const promise = cidLog.get(cid).catch(e => e);
                promises.push(promise);
            }
            yield cidLog.batch(ops);
            ops = [];
            let numEventsDeleted = 0;
            const watermarks = yield Promise.all(promises);
            for (const watermark of watermarks) {
                if (watermark) {
                    ops.push({ type: 'del', key: watermark });
                    numEventsDeleted += 1;
                }
            }
            const watermarkLog = yield tenantEventLog.partition('watermarks');
            yield watermarkLog.batch(ops);
            return numEventsDeleted;
        });
    }
    dump() {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            console.group('db');
            yield ((_b = (_a = this.db)['dump']) === null || _b === void 0 ? void 0 : _b.call(_a));
            console.groupEnd();
        });
    }
}
//# sourceMappingURL=event-log-level.js.map