local M = {}

local saveInterval = 5
local saveTimer = 0
local odometerValue = 0

local function getSaveFilePath()
  local folderName = string.sub(v.vehicleDirectory, 10, -2)
  return "settings/kenemation_mods_odometers/" .. folderName .. ".json"
end

local function saveOdometer()
  local path = getSaveFilePath()
  local data = { odometer = odometerValue }
  jsonWriteFile(path, data, true)
end

local function loadOdometer()
  local path = getSaveFilePath()
  local data = jsonReadFile(path)
  if data and type(data.odometer) == "number" then
    odometerValue = data.odometer
    electrics.values.nsx_gu_odometer = odometerValue
  end
end

local function updateGFX(dt)
  saveTimer = saveTimer + dt

  local speed = electrics.values.wheelspeed or 0
  local engineRunning = (electrics.values.engineRunning or 0) > 0.5

  if speed > 0.5 and speed < 600 and engineRunning then
    odometerValue = odometerValue + (speed * dt * 0.001)
    electrics.values.nsx_gu_odometer = odometerValue
  end

  if saveTimer >= saveInterval then
    saveOdometer()
    saveTimer = 0
  end
end

local function onInit()
  loadOdometer()
end

M.onInit = onInit
M.updateGFX = updateGFX
M.getValue = function() return odometerValue end
M.setValue = function(v) odometerValue = v or 0 end
M.saveOdometer = saveOdometer

return M