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



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

  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)
  }

  function handleAlbumInfoAdjust() {
    setIsShowAlbumInfo(!isShowAlbumInfo)
  }

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

export default App
