import { useEffect, useRef, useState } from "react";
import { formateLeftTime } from '@/utils/tools'

export default function useTimer(source) {
  const [list, setList] = useState([])
  const timerRef = useRef()

  useEffect(() => {
    if (!source || !source.length) {
      return;
    }

    const ticker = () => {
      const now = (new Date()).valueOf()

      const arr = source.map((it) => {
        const dt = (new Date(it.endTime)).valueOf()
        const ss = dt - now

        return [
          it[0],
          formateLeftTime(ss, 'min'),
        ]
      })

      setList(arr)
    }

    ticker()
    timerRef.current = setInterval(ticker, 1000 * 60)

    return () => clearInterval(timerRef.current)
  }, [source])

  return [list]
}
