import {
  useRef,
  useEffect,
  useCallback,
} from 'react'
import { useLocation } from 'react-router'

import round from 'lodash/round'

import { LogActions, logUserAction } from 'requests/logUserAction'

export const usePageLogger = (page?: string) => {
  const location = useLocation()
  const startTimeRef = useRef(new Date())

  const resetTime = useCallback(() => {
    startTimeRef.current = new Date()
  }, [])

  const getSpentTime = useCallback(() => (
    round((Date.now() - startTimeRef.current.getTime()) / 1000)
  ), [])

  const url = page || location.pathname

  const log = useCallback(() => {
    logUserAction({
      actionType: LogActions.PageChange,
      dateVisit: startTimeRef.current.toISOString(),
      duration: getSpentTime(),
      url,
    })
  }, [url, getSpentTime])

  useEffect(() => {
    resetTime()
    return log
  }, [
    page,
    log,
    resetTime,
  ])
}
