import { WSServer } from '../../ws.ts';
import { nanoid } from 'nanoid';

export const uuid = () => nanoid(16);

type VolcEngineBaseOptions = {
  url?: string;
  ws?: WebSocket;
  onConnect?: () => void;
  wsOptions?: {
    headers?: {
      'X-Api-Resource-Id'?: string;
      'X-Api-Access-Key'?: string;
      'X-Api-App-Key'?: string;
      'X-Api-Request-Id'?: string;
      Authorization?: string;
    };
  };
};
export class VolcEngineBase extends WSServer {
  canSend = false;
  isEnd: boolean = false;
  isError: boolean = false;
  
  constructor(opts: VolcEngineBaseOptions) {
    super({
      url: opts.url,
      ws: opts.ws,
      onConnect: opts.onConnect,
      wsOptions: opts.wsOptions,
    });
  }
  async onOpen() {
    console.log('VolcEngineBase onOpen');
    // 发送认证信息
    this.emitter.emit('open');
  }
  async isCanSend() {
    if (this.canSend) {
      return true;
    }
    return new Promise((resolve) => {
      this.emitter.once('canSend', () => {
        resolve(true);
      });
    });
  }
  async setCanSend(canSend: boolean) {
    this.canSend = canSend;
    if (canSend) {
      this.emitter.emit('canSend', canSend);
    }
  }
  async setIsEnd(isEnd: boolean) {
    this.isEnd = isEnd;
  }
}
