-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt

local M = {}
M.type = "auxiliary"
M.relevantDevice = nil

local htmlTexture = require("htmlTexture")

local min = math.min
local max = math.max

local gaugesScreenName = nil
local htmlPath = nil

local isAnalog = false

local updateTimer = 0
local updateFPS = 15
local invFPS = 1 / updateFPS

local volts = 0
local voltRampUpRate = 14*2

local function setUpdateFps(fps)
  updateFPS = fps
  invFPS = 1 / updateFPS
end

local function getIsEngineRunning()
  return (electrics.values["engineRunning"] or 0) > 0.5
end

local function isNaN( v ) return type( v ) == "number" and v ~= v end 

local function updateGFX(dt)
  if not getIsEngineRunning() then 
    volts = 0 
  else 
    volts = min(14, volts + (dt * voltRampUpRate))
  end
  
  --screen update
  updateTimer = updateTimer + dt
  if updateTimer > invFPS then
    -- set mileage or error text
    if isNaN(electrics.values["wheelspeed"] or 0) then
       if isAnalog then
          htmlTexture.call(gaugesScreenName, "setTextFromLua", {value=0})
        else
          htmlTexture.call(gaugesScreenName, "setTextFromLua", {value="service"})
        end
    else
      local mileage = odo.getValue() 
      htmlTexture.call(gaugesScreenName, "setMileageFromLua", {value=mileage})
    end
    
   --set volts
    if not isAnalog then
      htmlTexture.call(gaugesScreenName, "setVoltsFromLua", {value=volts})
    end
  end
end

local function init(jbeamData)
  gaugesScreenName = jbeamData.materialName
  htmlPath = jbeamData.htmlPath
  local unitType = jbeamData.unitType or "auto"
  if unitType == "auto" then
    unitType = settings.getValue("uiUnitLength") or "imperial"
  end
  
  local width = jbeamData.textureWidth or 180
  local height = jbeamData.textureHeight or 232
  isAnalog = jbeamData.isAnalog or false
  setUpdateFps(jbeamData.updateFps or 15)
  
  if not gaugesScreenName then
    log("E", "crownvicodohtml", "Got no material name for the texture, can't display anything...")
    M.updateGFX = nop
  else
    if htmlPath then
      htmlTexture.create(gaugesScreenName, htmlPath, width, height, updateFPS, "automatic")
      htmlTexture.call(gaugesScreenName, "init", {})
      htmlTexture.call(gaugesScreenName, "setUnitTypeFromLua", {units = unitType})
      if not isAnalog then
          htmlTexture.call(gaugesScreenName, "setVoltsFromLua", {value=0})
      end
      htmlTexture.call(gaugesScreenName, "setMileageFromLua", {value=0})
    else
      log("E", "crownvicodohtml", "Got no html path for the texture, can't display anything...")
      M.updateGFX = nop
    end
  end
end

M.init = init
M.updateGFX = updateGFX

return M
