import {useState} from "react";
import hostName from "./Config.ts";
import {AlbumInfo} from "./AlbumInfo.ts";

interface AlbumPlayerProps {
  albumHash: string,
  albumInfo: AlbumInfo
}

export default function AlbumPlayer(props: Readonly<AlbumPlayerProps>) {
  const [trackNum, setTrackNum] = useState<number>(0)
  const [isAlbumOver, setIsAlbumOver] = useState(false)

  let album = props.albumInfo
  function handleNextTrack() {
    if(!isAlbumOver && trackNum+1 === props.albumInfo.trackList.length) {
      setIsAlbumOver(true)
    } else {
      setTrackNum(trackNum+1)
    }

  }

  if(props.albumHash && album) {
    console.log(album)
    return (
        <div className={"player"}>
          <div>{album.trackList[trackNum].trackArtist} - {album.trackList[trackNum].trackTitle}</div>
          <audio title={album.trackList[trackNum].trackTitle} controls={true} autoPlay={true} preload={"metadata"}
                 src={`${hostName}/music/album/${props.albumHash}/track/${trackNum}`}
                 onEnded={handleNextTrack} />
        </div>
    )
  } else {
    return <div className={"player"}></div>
  }
}