import { ref } from 'vue'
import { fetchDevices, fetchPositions } from 'src/api/traccar'

let __gpsStarted = false
let __gpsInterval = null
let __gpsPolling = false

export function useGpsTracking (technicians) {
  const traccarDevices = ref([])
  const _techsByDevice = {}

  function _buildTechDeviceMap () {
    Object.keys(_techsByDevice).forEach(k => delete _techsByDevice[k])
    technicians.value.forEach(t => {
      if (!t.traccarDeviceId) return
      const dev = traccarDevices.value.find(d => d.id === parseInt(t.traccarDeviceId) || d.uniqueId === t.traccarDeviceId)
      if (dev) _techsByDevice[dev.id] = t
    })
  }

  function _applyPositions (positions) {
    positions.forEach(p => {
      const tech = _techsByDevice[p.deviceId]
      if (!tech || !p.latitude || !p.longitude) return
      const cur = tech.gpsCoords
      if (!cur || Math.abs(cur[0] - p.longitude) > 0.00001 || Math.abs(cur[1] - p.latitude) > 0.00001) {
        tech.gpsCoords = [p.longitude, p.latitude]
      }
      tech.gpsSpeed = p.speed || 0
      tech.gpsTime = p.fixTime
      tech.gpsOnline = true
    })
  }

  async function pollGps () {
    if (__gpsPolling) return
    __gpsPolling = true
    try {
      if (!traccarDevices.value.length) traccarDevices.value = await fetchDevices()
      _buildTechDeviceMap()
      const deviceIds = Object.keys(_techsByDevice).map(Number)
      if (!deviceIds.length) return
      const positions = await fetchPositions(deviceIds)
      _applyPositions(positions)
      // Mark techs with no position as offline
      Object.values(_techsByDevice).forEach(t => {
        if (!positions.find(p => _techsByDevice[p.deviceId] === t)) t.gpsOnline = false
      })
    } catch { /* poll error */ }
    finally { __gpsPolling = false }
  }

  async function startGpsTracking () {
    if (__gpsStarted) return
    __gpsStarted = true
    await pollGps()
    __gpsInterval = setInterval(pollGps, 30000)
  }

  function stopGpsTracking () {
    __gpsStarted = false
    if (__gpsInterval) { clearInterval(__gpsInterval); __gpsInterval = null }
  }

  return { traccarDevices, pollGps, startGpsTracking, stopGpsTracking }
}
