import Head from "next/head";
import { useRouter } from "next/router"
import React from "react"

const WHEP_API_LOCATION = "/api/wish-server/whep"

const Video = ({user}: {user: string}) => {
  const videoRef = React.createRef<HTMLVideoElement>();
  React.useEffect(() => {
    const peerConnection = new RTCPeerConnection()

    peerConnection.ontrack = function (event) {
      videoRef.current!.srcObject = event.streams[0]
    }
  
    peerConnection.addTransceiver('audio')
    peerConnection.addTransceiver('video')


    peerConnection.createOffer().then(async offer => {
      peerConnection.setLocalDescription(offer)

      const response = await fetch(WHEP_API_LOCATION, {
        method: 'POST',
        body: offer.sdp,
        headers: {
          Authorization: `Bearer ${user}`,
          'Content-Type': 'application/sdp'
        }
      })

      if (response.status >= 200 && response.status < 300) {
        const sdp = await response.text();
        peerConnection.setRemoteDescription({
          sdp,
          type: 'answer'
        })
      }
    })

    return function cleanup() {
      peerConnection.close()
    }
  }, [videoRef, user])

  return <video ref={videoRef} autoPlay muted controls playsInline />
}

export default () => {
  const router = useRouter()
  const { user } = router.query;
  const Player = ({ user }: { user: any }) => {
    if (typeof user !== "string") {
      return <>
        <strong>The requested user was not found.</strong>
      </>
    }

    return <>
      <Video user={user}></Video>
    </>
  }

  return <>
    <Head>
      <title>{`${user} | live.umm.gay`}</title>
    </Head>

    <main>
      <h1>watching: {user}</h1>
      <Player user={user}/>
      {/* TODO: Chat? */}
    </main>
  </>
}
