import { hashId } from '../utils';
export interface MessageData {
  type: string;
  data: any;
  uuid: string;
}

export class Messager {
  private records: Record<string, any> = {};
  constructor(private worker: Worker) {
    this.worker.addEventListener('message', this.onMessage.bind(this));
  }
  onMessage(e: MessageEvent) {
    const { type, data, uuid } = e.data as MessageData;
    if (this.records[uuid]) {
      this.records[uuid](data);
      delete this.records[uuid];
    }
  }
  send(type: string, data: any) {
    const id = hashId();
    this.worker.postMessage({
      type,
      data,
      uuid: id
    });
    return new Promise((resolve, reject) => {
      this.records[id] = resolve;
      setTimeout(reject, 30 * 1000, 'timeout');
    });
  }
  dispose() {
    this.worker.removeEventListener('message', this.onMessage);
    this.worker.terminate();
  }
}
