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

local htmlTexture = require("htmlTexture")

local gaugesScreenName = nil
local htmlPath = nil

local updateTimer = 0
local updateFPS = 30
local invFPS = 1 / updateFPS
local direction
local compassEnabled = false
local infotainment = false
local function updateGFX(dt)
  updateTimer = updateTimer + dt
  if updateTimer > invFPS then
    local data = {}
	
    data.radio = electrics.values["radio"]
    data.temp = obj:getEnvTemperature() - 273.15
    data.clock = os.date("%H") .. ":" .. os.date("%M")
	data.volume = electrics.values["radioVolume"]
	data.volumeChanged = electrics.values["volumeChanged"]
	
	if infotainment == false then
		data.inputText = "CD"
	else
		data.inputText = "DVD"
	end
	
	if electrics.values["radioAuthor"] == "Unknown" then
		data.radioAuthor = " "
	else
		data.radioAuthor = electrics.values["radioAuthor"]
	end
	if compassEnabled == true then
		direction = math.deg(obj:getDirection()) + 180

		if direction >= 337.5 and direction <= 360 then
			data.compass = "N"
		elseif direction >= 0 and direction < 22.5 then
			data.compass = "N"
		elseif direction >= 22.5 and direction < 67.5 then
			data.compass = "NW"
		elseif direction >= 67.5 and direction < 112.5 then
			data.compass = "W"
		elseif direction >= 112.5 and direction < 157.5 then
			data.compass = "SW"
		elseif direction >= 157.5 and direction < 202.5 then
			data.compass = "S"
		elseif direction >= 202.5 and direction < 247.5 then
			data.compass = "SE"
		elseif direction >= 247.5 and direction < 292.5 then
			data.compass = "E"
		elseif direction >= 292.5 and direction < 337.5 then
			data.compass = "NE"
		end
	else
		data.compass = " "
	end

    data.radiotempunit = settings.getValue("uiUnitLength") or "metric"

	data.enginerunning = electrics.values["engineRunning"]

    --dump(data)
    htmlTexture.call(gaugesScreenName, "update", data)
    updateTimer = 0
  end
end

local function init(jbeamData)
	infotainment = jbeamData.infotainment or false
	compassEnabled = jbeamData.compassEnabled or false
	gaugesScreenName = jbeamData.materialName
	htmlPath = jbeamData.htmlPath
	local width = jbeamData.textureWidth or 512
	local height = jbeamData.textureHeight or 256

    htmlTexture.create(gaugesScreenName, htmlPath, width, height, updateFPS, "automatic")
    htmlTexture.call(gaugesScreenName, "init")
end

M.init = init
M.updateGFX = updateGFX

return M
