import { RequestUiMetaKind } from "@api-client/core/build/browser.js";
import { StoreBroadcast } from "../StoreBroadcast.js";
import { IdbStore } from "./IdbStore.js";
export class IdbProjectUi extends IdbStore {
    constructor() {
        super(...arguments);
        this.channel = new BroadcastChannel(StoreBroadcast.projectUi);
    }
    async clear(key) {
        const tx = this.db.transaction('ProjectUi', 'readwrite');
        const index = tx.store.index('project');
        const items = await index.getAll(key);
        await Promise.all(items.map(item => tx.store.delete([item.meta.project, item.meta.key])));
        items.forEach(item => {
            this.notifyDeleted(item.meta.project, item.meta.key);
        });
        return {
            key,
        };
    }
    async set(pid, key, meta) {
        const value = {
            data: meta,
            meta: { project: pid, key, },
        };
        await this.db.put('ProjectUi', value);
        const event = {
            type: 'event',
            operation: 'created',
            kind: RequestUiMetaKind,
            key,
            project: pid,
            data: meta,
            space: '',
            path: '/projects/ui',
        };
        this.channel.postMessage(event);
        return {
            key,
            parent: pid,
            item: meta,
            kind: RequestUiMetaKind,
        };
    }
    async get(pid, key) {
        const item = await this.db.get('ProjectUi', [pid, key]);
        if (item) {
            return item.data;
        }
        return undefined;
    }
    async getBulk(pid, keys) {
        const { store } = this.db.transaction('ProjectUi', 'readonly');
        const items = await Promise.all(keys.map(key => store.get([pid, key])));
        const result = items.map((item) => {
            if (item) {
                return item.data;
            }
            return undefined;
        });
        return {
            items: result,
        };
    }
    async delete(pid, key) {
        await this.db.delete('ProjectUi', [pid, key]);
        this.notifyDeleted(pid, key);
        return {
            key,
            kind: RequestUiMetaKind,
            parent: pid,
        };
    }
    notifyDeleted(projectId, requestId) {
        const event = {
            type: 'event',
            operation: 'deleted',
            kind: RequestUiMetaKind,
            key: requestId,
            project: projectId,
            space: '',
            path: '/projects/ui',
        };
        this.channel.postMessage(event);
    }
}
//# sourceMappingURL=IdbProjectUi.js.map