import { AudioRecorder, AudioRecorderConfig } from "../audio";
import { EventEmitter } from "events";

export interface RecorderEvents {
  start: [null];
  stop: [null];
  error: [{ data: Error }];
  dataAvailable: [{ data: ArrayBuffer }];
  frequency: [{ data: Uint8Array }];
}

export class Recorder extends EventEmitter {
  private recorder: AudioRecorder;

  constructor() {
    super();
    this.recorder = new AudioRecorder();
    this.recorder.onStart = this.onStart;
    this.recorder.onStop = this.onStop;
    this.recorder.onError = this.onError;
    this.recorder.onDataAvailable = this.onDataAvailable;
    this.recorder.onFrequency = this.onFrequency;
  }

  start = (options?: AudioRecorderConfig) => {
    this.recorder.start(options);
  };

  stop = () => {
    this.recorder.stop();
  };

  private onStart = () => {
    this.emit("start", null);
  };

  private onStop = () => {
    this.emit("stop", null);
  };

  private onError = (error: Error) => {
    this.emit("error", { data: error });
  };

  private onDataAvailable = (data: ArrayBuffer) => {
    this.emit("dataAvailable", { data });
  };

  private onFrequency = (event: { data: Uint8Array }) => {
    this.emit("frequency", { data: event.data });
  };
}
