import { 
  ContextChangeRecord, ContextDeleteRecord, 
  IBulkOperationResult, 
  IQueryResponse, IRequestUiMeta, IUrl
} from "@api-client/core/build/browser.js";
import { HttpClientStore } from "./HttpClientStore.js";
import { SharedWorkerThread } from "../../bindings/base/SharedWorkerThread.js";
import { HttpClientIdbDatabase } from "./HttpClientIdbDatabase.js";

/**
 * A logic running in the shared worker that accesses datastore for API Client.
 */
export class IdbThread extends SharedWorkerThread implements HttpClientStore {
  store = new HttpClientIdbDatabase();

  async initializeStore(): Promise<void> {
    await this.store.initialize();
  }

  wsHistory = {
    add: (url: string): Promise<IUrl> => this.store.wsHistory.add(url),
    query: (query: string): Promise<IQueryResponse<IUrl>> => this.store.wsHistory.query(query),
    delete: (url: string): Promise<ContextDeleteRecord> => this.store.wsHistory.delete(url),
    clear: (): Promise<void> => this.store.wsHistory.clear(),
  }

  urlHistory = {
    add: (url: string): Promise<IUrl> => this.store.urlHistory.add(url),
    query: (query: string): Promise<IQueryResponse<IUrl>> => this.store.urlHistory.query(query),
    delete: (url: string): Promise<ContextDeleteRecord> => this.store.urlHistory.delete(url),
    clear: (): Promise<void> => this.store.urlHistory.clear(),
  }

  projectUi = {
    clear: (key: string): Promise<ContextDeleteRecord> => this.store.projectUi.clear(key),
    set: (pid: string, key: string, meta: IRequestUiMeta): Promise<ContextChangeRecord<IRequestUiMeta>> => this.store.projectUi.set(pid, key, meta),
    get: (pid: string, key: string): Promise<IRequestUiMeta | undefined> => this.store.projectUi.get(pid, key),
    getBulk: (pid: string, keys: string[]): Promise<IBulkOperationResult<IRequestUiMeta>> => this.store.projectUi.getBulk(pid, keys),
    delete: (pid: string, key: string): Promise<ContextDeleteRecord> => this.store.projectUi.delete(pid, key),
  }
}

// Probably this should go to a separate file...
const instance = new IdbThread();
instance.initialize();
