import type { Song } from '~/types/song'

export function usePlaylist() {
  const store = usePlayerStore()
  const bookData = useBookData()
  const { loadAndPlay } = useAudioPlayer()

  async function loadFullPlaylist() {
    await bookData.init()
    const songs = bookData.getPlaylistOrder()
    store.setPlaylist(songs)
  }

  function shufflePlaylist() {
    const current = [...store.playlist]
    // Fisher-Yates shuffle
    for (let i = current.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1))
      ;[current[i], current[j]] = [current[j], current[i]]
    }
    store.setPlaylist(current)
    store.toggleShuffle()
  }

  function unshuffle() {
    const songs = bookData.getPlaylistOrder()
    store.setPlaylist(songs)
    store.toggleShuffle()
  }

  function playSongFromPlaylist(song: Song) {
    loadAndPlay(song)
  }

  function toggleShuffle() {
    if (store.isShuffled) {
      unshuffle()
    }
    else {
      shufflePlaylist()
    }
  }

  return {
    loadFullPlaylist,
    shufflePlaylist,
    unshuffle,
    playSongFromPlaylist,
    toggleShuffle,
  }
}
