import { useCallback } from 'react'

import type { SetPartialState } from 'hooks'

import type { Chapters } from '../types'
import type { PlayerState } from '.'
import { findChapterByProgress } from '../helpers'

type Args = {
  chapters: Chapters,
  duration: number,
  setPlayerState: SetPartialState<PlayerState>,
}

export const useProgressChangeHandler = ({
  chapters,
  duration,
  setPlayerState,
}: Args) => {
  const onProgressChange = useCallback((progress: number, seeking: boolean) => {
    setPlayerState((state) => {
      // значение новой позиции ползунка в миллисекундах
      const progressMs = progress * duration
      const chapterIndex = findChapterByProgress(chapters, progressMs)
      const chapter = chapters[chapterIndex]
      const isProgressOnDifferentChapter = (
        chapterIndex !== -1
        && chapterIndex !== state.activeChapterIndex
      )
      const nextChapter = isProgressOnDifferentChapter
        ? chapterIndex
        : state.activeChapterIndex

      // отнимаем начало главы на котором остановились от общего прогресса
      // чтобы получить прогресс текущей главы
      const chapterProgressMs = (progressMs - chapter.startMs)
      const seekMs = chapterProgressMs + chapter.startOffsetMs
      return {
        activeChapterIndex: nextChapter,
        playedProgress: chapterProgressMs,
        seek: {
          ...state.seek,
          [state.activePlayer]: seekMs / 1000,
        },
        seeking,
      }
    })
  }, [duration, chapters, setPlayerState])

  return onProgressChange
}
