import { getKeyValueStore } from "../data/index.js";
import { dispatchEvent } from "../events/index.js";
import { ok } from "../is.js";
import { caches } from "../fetch/index.js";
import { CONTENT_INDEX_DEFER_ICONS, getConfig } from "../config/index.js";
const STORE_NAME = "contentIndex";
function getContentIndexStore() {
    return getKeyValueStore(STORE_NAME, {
        counter: false
    });
}
export class DurableContentIndex {
    async add(contentDescription) {
        ok(contentDescription.id, "id should not be empty");
        ok(contentDescription.title, "title should not be empty");
        ok(contentDescription.description, "description should not be empty");
        ok(contentDescription.url, "url should not be empty");
        const store = getContentIndexStore();
        if (!CONTENT_INDEX_DEFER_ICONS && contentDescription.icons?.length) {
            const cache = await caches.open(STORE_NAME);
            // Fetch icons _before_ storing, indicates that all the resources are accessible
            await cache.addAll(contentDescription.icons.map(({ src }) => src));
        }
        await store.set(contentDescription.id, contentDescription);
        await dispatchEvent({
            type: "fetch",
            request: {
                url: contentDescription.url
            },
            cache: {
                name: STORE_NAME
            },
            dispatch: {
                type: "content",
                id: contentDescription.id
            }
        });
    }
    async delete(id) {
        const store = getContentIndexStore();
        const exists = await store.get(id);
        if (!exists) {
            return;
        }
        await store.delete(id);
        await dispatchEvent({
            type: "contentdelete",
            id
        });
    }
    async getAll() {
        const store = getContentIndexStore();
        const { index } = getConfig();
        const stored = await store.values();
        const value = (isContentIndexInitFn(index) ?
            await index() :
            index);
        if (!value)
            return stored;
        return stored.concat(value);
        function isContentIndexInitFn(value) {
            return typeof value === "function";
        }
    }
}
export const index = new DurableContentIndex();
//# sourceMappingURL=content-index.js.map