import { HttpClientStoreBindings } from "../base/HttpClientStoreBindings.js";
/**
 * HTTP Client's specific data (URL history, UI state, etc).
 */
export class WebHttpClientStoreBindings extends HttpClientStoreBindings {
    constructor(app, workerUrl) {
        super(app);
        this.workerUrl = workerUrl;
        this.wsHistory = {
            add: (url) => this.invoke('wsHistory.add', url),
            query: (query) => this.invoke('wsHistory.query', query),
            delete: (url) => this.invoke('wsHistory.delete', url),
            clear: () => this.invoke('wsHistory.clear'),
        };
        this.urlHistory = {
            add: (url) => this.invoke('urlHistory.add', url),
            query: (query) => this.invoke('urlHistory.query', query),
            delete: (url) => this.invoke('urlHistory.delete', url),
            clear: () => this.invoke('urlHistory.clear'),
        };
        this.projectUi = {
            clear: (key) => this.invoke('projectUi.clear', key),
            set: (pid, key, meta) => this.invoke('projectUi.set', pid, key, meta),
            get: (pid, key) => this.invoke('projectUi.get', pid, key),
            getBulk: (pid, keys) => this.invoke('projectUi.getBulk', pid, keys),
            delete: (pid, key) => this.invoke('projectUi.delete', pid, key),
        };
    }
    async initialize() {
        await this.createWorker();
        await this.initializeStore();
        await super.initialize();
    }
    async initializeStore() {
        await this.invoke('initializeStore');
    }
    async createWorker() {
        return new Promise((resolve, reject) => {
            const worker = new SharedWorker(this.workerUrl, {
                type: 'module',
                name: 'HttpClientStore',
            });
            worker.port.start();
            worker.onerror = () => reject(new Error('Unable to initialize the IO process.'));
            this.worker = worker;
            const binder = this.ioHandler.bind(this);
            worker.port.addEventListener('message', function init() {
                // the ready message.
                worker.port.removeEventListener('message', init);
                worker.port.addEventListener('message', binder);
                resolve();
            });
            setTimeout(() => {
                worker.port.postMessage('init');
            }, 1);
        });
    }
    sendIoCommand(cmd) {
        const { worker } = this;
        if (!worker) {
            throw new Error(`IO not ready.`);
        }
        worker.port.postMessage(cmd);
    }
    ioHandler(e) {
        if (e.data === 'ready') {
            return;
        }
        const event = e.data;
        this.handleIoMessage(event);
    }
}
//# sourceMappingURL=WebHttpClientStoreBindings.js.map