import { Checker } from './Checker'
import { Room } from 'livekit-client'

export class TURNCheck extends Checker {
  name = 'TURNCheck'

  get description(): string {
    return 'Can connect via TURN'
  }

  async perform(): Promise<void> {
    console.log(this.connectOptions)

    const room = new Room()
    const signalClient = room.engine.client

    const joinRes = await signalClient.join(this.url, this.token, {
      autoSubscribe: true,
      maxRetries: 0,
    })

    const iceServers = this.connectOptions?.rtcConfig?.iceServers ?? joinRes.iceServers

    let hasTLS = false
    let hasTURN = false
    let hasSTUN = false

    for (let iceServer of iceServers) {
      for (let url of iceServer.urls) {
        if (url.startsWith('turn:')) {
          hasTURN = true
          hasSTUN = true
        } else if (url.startsWith('turns:')) {
          hasTURN = true
          hasSTUN = true
          hasTLS = true
        }
        if (url.startsWith('stun:')) {
          hasSTUN = true
        }
      }
    }
    if (!hasSTUN) {
      this.appendWarning('No STUN servers configured on server side.')
    } else if (hasTURN && !hasTLS) {
      this.appendWarning('TURN is configured server side, but TURN/TLS is unavailable.')
    }
    await signalClient.close()
    if (this.connectOptions?.rtcConfig?.iceServers || hasTURN) {
      //this.room.engine.rtcConfig.iceServers = rtcIceServers
      await this.room!.connect(this.url, this.token, {
        rtcConfig: {
          iceTransportPolicy: 'relay',
          iceServers: iceServers,
        },
      })
    } else {
      this.appendWarning('No TURN servers configured.')
      this.skip()
      await new Promise((resolve) => setTimeout(resolve, 0))
    }
  }
}
