import {
  useRef,
  useEffect,
  useCallback,
} from 'react'

import round from 'lodash/round'

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

import { useEventListener } from 'hooks'
import { useLocation } from 'react-router'

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,
  ])

  useEventListener({
    callback: log,
    event: 'beforeunload',
  })
}
