import React, {useEffect, useState} from 'react'
import './App.css'
import {AlbumMetadata} from "./AlbumMetadata.ts"
import PhotoContainer from "./PhotoContainer.tsx";
import AlbumPlayer from "./AlbumPlayer.tsx";
import hostName from "./Config.ts";
import {AlbumInfo} from "./AlbumInfo.ts";



function App() {
  const [albums, setAlbums] = useState(Array<AlbumMetadata>)
  const [selectedAlbum, setSelectedAlbum] = useState("")
  const [albumInfo, setAlbumInfo] = useState<AlbumInfo>()

  useEffect(() => {
    let fetched = fetch(`${hostName}/album`)
    fetched.then(response => {
      if(response.ok) {
        response.json().then( body =>
            setAlbums(body)
        )
      }
    })
  }, [])

  useEffect(() => {
    if (selectedAlbum) {
      let fetched = fetch(`${hostName}/album/${selectedAlbum}`)
      fetched.then(response => {
        if (response.ok) {
          response.json().then(body =>
              setAlbumInfo(body)
          )
        }
      })
    }
  }, [selectedAlbum])

  function handleAlbumClick(event: React.MouseEvent<HTMLElement>) {
    setSelectedAlbum(event.currentTarget.id)
  }

  return (
      <div className={"gallery"}>
        <PhotoContainer imageList={albums} albumClickHandler={handleAlbumClick}/>
        {albumInfo ? <AlbumPlayer albumHash={selectedAlbum} albumInfo={albumInfo} key={selectedAlbum}/> : <div></div> }
      </div>
  )
}

export default App
