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 { BehaviorSubject, defer, filter, from, mergeMap, tap, } from 'rxjs';
import { v4 as uuidv4 } from 'uuid';
class DeferredDbSaver {
    get queue() {
        return this.queue$.getValue();
    }
    constructor(dbInstance$) {
        this.queue$ = new BehaviorSubject(new Map());
        dbInstance$.subscribe((db) => {
            this.dbApi = db;
        });
        dbInstance$
            .pipe(filter((dbInstance) => !!dbInstance), tap(() => console.log('DeferredDbSaver - initialized')), mergeMap(() => this.queue$), filter((queue) => queue.size > 0), mergeMap((queue) => defer(() => from(this.processQueue(queue)))))
            .subscribe({
            error: (err) => console.error('Error processing IPFS queue', err),
        });
    }
    enqueueIpfsContent(content) {
        if (!content) {
            return;
        }
        const { cid } = content;
        this.queue$.next(new Map(this.queue$.value).set(cid, { content }));
    }
    enqueueLinks(links) {
        if (!links || !links.length) {
            return;
        }
        const id = uuidv4();
        this.queue$.next(new Map(this.queue$.value).set(id, { links }));
    }
    processQueue(queue) {
        return __awaiter(this, void 0, void 0, function* () {
            this.queue$.next(new Map());
            for (const [cid, item] of queue) {
                yield this.processQueueItem(item);
                queue.delete(cid);
            }
        });
    }
    processQueueItem(queueItem) {
        return __awaiter(this, void 0, void 0, function* () {
            const { content, links } = queueItem;
        });
    }
}
export default DeferredDbSaver;
//# sourceMappingURL=DeferredDbSaver.js.map