class Recorder {
  mediaRecorder: MediaRecorder | undefined;
  recordedBlobs: any[];
  recording = false;

  constructor(stream: MediaStream, options?: MediaRecorderOptions) {
    this.recordedBlobs = [];
    this.recordStream(stream, options);
  }

  recordStream = (stream: MediaStream, options?: MediaRecorderOptions) => {
    let _mediaRecorder: MediaRecorder | undefined = undefined;

    try {
      _mediaRecorder = new MediaRecorder(stream, options);
    } catch (e0) {
      console.log('Unable to create MediaRecorder with options Object: ', options, e0);
      try {
        options = { mimeType: 'video/webm;codecs=vp8' };
        _mediaRecorder = new MediaRecorder(stream, options);
      } catch (e1) {
        console.log('Unable to create MediaRecorder with options Object: ', options, e1);
        try {
          _mediaRecorder = new MediaRecorder(stream);
        } catch (e2) {
          alert('MediaRecorder is not supported by this browser.');
          console.log('Unable to create MediaRecorder', e2);
        }
      }
    }

    this.mediaRecorder = _mediaRecorder || undefined;
    if (this.mediaRecorder) {
      this.mediaRecorder.onstop = this.handleStop;
      this.mediaRecorder.ondataavailable = this.handleDataAvailable;
      this.recording = true;
      this.mediaRecorder.start(10);
    }
  };

  handleStop = (event: Event) => {
    console.log('Recorder stopped: ', event);
  };

  handleDataAvailable = (event: BlobEvent) => {
    if (event.data && event.data.size > 0) {
      this.recordedBlobs.push(event.data);
    }
  };

  stop = () => {
    this.recording = false;
    this.mediaRecorder?.stop();
  };

  get src() {
    if (this.state === 'recording') {
      return '';
    }
    var type = (this.recordedBlobs[0] || {}).type;
    var superBuffer = new Blob(this.recordedBlobs, { type });
    return window.URL.createObjectURL(superBuffer);
  }

  get state() {
    return this.mediaRecorder?.state;
  }

  download = () => {
    const blob = new Blob(this.recordedBlobs, { type: 'video/webm' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'test.webm';
    document.body.appendChild(a);
    a.click();
    setTimeout(function () {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 100);
  };
}

export default Recorder;
