let requestId = 0;
function callServiceWorker(obj, 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;
            //log(['SW response', msg]);
            if (msg?.id !== id) {
                return;
            }
            if (msg.error) {
                obj.lastErr = msg.error;
            }
            if (msg.ok) {
                resolve(msg.result);
            }
            else {
                reject(new Error(msg.error || 'IndexedDB service worker error'));
            }
            channel.port1.close();
        };
        const command = {
            id,
            database: obj.dbName,
            method,
            args
        };
        navigator.serviceWorker.controller.postMessage(command, [channel.port2]);
    });
}
export default class bbnDbObjectProxy {
    _dbName;
    lastErr = null;
    constructor(dbName) {
        this._dbName = dbName;
    }
    get dbName() {
        return this._dbName;
    }
    insert(table, data) {
        return callServiceWorker(this, 'object.insert', [table, data]);
    }
    update(table, data, where, replace = false) {
        return callServiceWorker(this, 'object.update', [table, data, where, replace]);
    }
    delete(table, where) {
        return callServiceWorker(this, 'object.delete', [table, where]);
    }
    selectOne(table, field, where, order, start, limit) {
        return callServiceWorker(this, 'object.selectOne', [table, field, where, order, start, limit]);
    }
    select(table, fields, where, order, start) {
        return callServiceWorker(this, 'object.select', [table, fields, where, order, start]);
    }
    selectAll(table, fields, where, order, start, limit) {
        return callServiceWorker(this, 'object.selectAll', [table, fields, where, order, start, limit]);
    }
    getColumnValues(table, field, where, order, start, limit) {
        return callServiceWorker(this, 'object.getColumnValues', [table, field, where, order, start, limit]);
    }
    count(table, where) {
        return callServiceWorker(this, 'object.count', [table, where]);
    }
    copyTable(target, table, fields, where, order, start, limit) {
        return callServiceWorker(this, 'object.copyTable', [target, table, fields, where, order, start, limit]);
    }
    deleteTable(table) {
        return callServiceWorker(this, 'object.deleteTable', [table]);
    }
    close() {
        void callServiceWorker(this, 'object.close', []);
    }
    lastError() {
        return callServiceWorker(this, 'object.lastError', [this.dbName]);
    }
}
