import {useEffect, useState} from "react";
import hostName from "./Config.ts";
import {TrackInfo} from "./TrackInfo.tsx";

interface AlbumPlayerProps {
  albumHash: string
}

export default function AlbumPlayer(props: Readonly<AlbumPlayerProps>) {
  const [trackNum, setTrackNum] = useState(1)
  const [trackInfo, setTrackInfo] = useState<TrackInfo>()

  useEffect(() => {
    if (props.albumHash) {
      let fetched = fetch(`${hostName}/track/${props.albumHash}/${trackNum}`)
      fetched.then(response => {
        if (response.ok) {
          response.json().then(body => {
                setTrackInfo(body)
              }
          )
        }
      })
    }
  }, [props.albumHash, trackNum])

  function handleNextTrack() {
    setTrackNum(trackNum+1)
  }

  if(props.albumHash) {
    return (
        <div className={"player"}>
          <div>{trackInfo?.artist ?? ""} - {trackInfo?.trackTitle ?? ""}</div>
          <audio title={trackInfo?.trackTitle} controls={true} autoPlay={true} preload={"metadata"}
                 src={`${hostName}/music/album/${props.albumHash}/${trackNum}`}
                 onEnded={handleNextTrack} />
        </div>
    )
  } else {
    return <div className={"player"}></div>
  }
}