import bbnDbObjectProxy from './ObjectProxy.js';
let requestId = 0;
function callServiceWorker(database, method, args) {
    return new Promise((resolve, reject) => {
        if (!navigator.serviceWorker?.controller) {
            reject(new Error('No active service worker controller'));
            return;
        }
        const id = ++requestId;
        const channel = new MessageChannel();
        channel.port1.onmessage = event => {
            const msg = event.data;
            if (msg?.id !== id) {
                return;
            }
            if (msg.ok) {
                resolve(msg.result);
            }
            else {
                reject(new Error(msg.error || 'IndexedDB service worker error'));
            }
            channel.port1.close();
        };
        const command = {
            id,
            database,
            method,
            args
        };
        navigator.serviceWorker.controller.postMessage(command, [channel.port2]);
    });
}
const bbnDbProxy = {
    ok: true,
    async open(database, version) {
        await callServiceWorker(database, 'manager.open', [database, version]);
        return new bbnDbObjectProxy(database);
    },
    async add(database, name, structure) {
        return await callServiceWorker(database, 'manager.add', [database, name, structure]);
    },
    async remove(database, name) {
        return await callServiceWorker(database, 'manager.remove', [database, name]);
    },
    async importStructure(database, structure) {
        return await callServiceWorker(database, 'manager.importStructure', [database, structure]);
    },
    async close(database) {
        return await callServiceWorker(database, 'manager.close', [database]);
    }
};
export default bbnDbProxy;
