import React, { useEffect, useRef, useState } from 'react'
import { throttle } from 'throttle-debounce'
import short from 'short-uuid'

const updateProperties = () => {
  const [promises, setPromises] = useState([])
  const ids = useRef([])
  const callbacks = useRef([])
  const [latestState, setLatestState] = useState({})
  const [loading, setLoading] = useState(false)

  const addPromise = (promise, callback) => {
    const newPromiseId = short.generate()
    setPromises([...promises, promise])
    ids.current = [...ids.current, newPromiseId]
    callbacks.current = [...callbacks.current, callback]
    return newPromiseId
  }

  const executePromises = throttle(750, async () => {
    setLoading(true)
    for (let i = 0; i < promises.length; i++) {
      try {
        const promiseResult = await promises[i]
        setLatestState({
          id: ids.current[i],
          data: promiseResult
        })
        if (callbacks.current[i]) {
          callbacks.current[i](promiseResult, ids.current[i])
        }
      } catch (e) {
        console.error(e)
        callbacks.current[i](null, ids.current[i], e)
      }
    }
    setLoading(false)
    setPromises([])
    ids.current = []
    callbacks.current = []
  })

  useEffect(() => {
    if (promises.length) {
      executePromises()
    }
  }, [promises])

  return {
    addPromise,
    latestState,
    loading
  }
}

export default updateProperties
