import { Checker } from './Checker'

export class MediaDevicesCheck extends Checker {
  name = 'MediaDevicesCheck'

  get description(): string {
    return 'Can get media devices.'
  }

  async perform(): Promise<void> {
    this.appendMessage('Check permissions')
    const mediaDevices = []

    for (const kind of ['audio', 'video']) {
      try {
        const constraints = { [kind]: true }
        const stream = await navigator.mediaDevices.getUserMedia(constraints)
        stream.getTracks().forEach((t: MediaStreamTrack) => t.stop())
        const devices = await navigator.mediaDevices.enumerateDevices()
        const filtered = devices.filter((d) => d.kind.startsWith(kind))
        mediaDevices.push(...filtered)
      } catch (e) {
        console.error(e)
        this.appendError(`Permission denied: ${kind}`)
      }
    }
    if (mediaDevices.length > 0) {
      this.appendMessage(
        mediaDevices.map((device) => {
          return { kind: device.kind, label: device.label }
        })
      )
      console.log(mediaDevices)
    }
  }
}
