-- 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 = 'auxilliary'
M.relevantDevice = nil

local blinkTimerThreshold_1 = 0.2
local blinkTimerThreshold_2 = 0.4
local blinkTimerThreshold_3 = 0.6
local blinkTimerThreshold_4 = 0.8
local blinkTimer = 0
local blinkPulse_1 = 0
local blinkPulse_2 = 0
local blinkPulse_3 = 0

local function init()
	electrics.values['signal_RL_1'] = 0
	electrics.values['signal_RL_2'] = 0
	electrics.values['signal_RL_3'] = 0

	electrics.values['signal_RR_1'] = 0
	electrics.values['signal_RR_2'] = 0
	electrics.values['signal_RR_3'] = 0
	
	electrics.values['lowhighbeam_RL_1'] = 0
	electrics.values['lowhighbeam_RL_2'] = 0
	electrics.values['lowhighbeam_RL_3'] = 0

	electrics.values['lowhighbeam_RR_1'] = 0
	electrics.values['lowhighbeam_RR_2'] = 0
	electrics.values['lowhighbeam_RR_3'] = 0
	
	electrics.values['tneedle'] = 0
	
end

local function generateBlinkPulse(dt)
  blinkTimer = blinkTimer + dt
  if blinkTimer > blinkTimerThreshold_1 then
    blinkPulse_1 = 1
  end
  if blinkTimer > blinkTimerThreshold_2 then
    blinkPulse_2 = 1
  end
  if blinkTimer > blinkTimerThreshold_3 then
    blinkPulse_3 = 1
  end
  if blinkTimer > blinkTimerThreshold_4 then
    blinkPulse_1 = 0  
	blinkPulse_2 = 0
	blinkPulse_3 = 0
    blinkTimer = 0

  end
end

local function updateGFX(dt)

    local vals = M.values
    generateBlinkPulse(dt)
	
	electrics.values['signal_RL_1'] = (electrics.values["signal_left_input"] == 1 and blinkPulse_1)
	electrics.values['signal_RL_2'] = (electrics.values["signal_left_input"] == 1 and blinkPulse_2)
	electrics.values['signal_RL_3'] = (electrics.values["signal_left_input"] == 1 and blinkPulse_3)
	
	electrics.values['signal_RR_1'] = (electrics.values["signal_right_input"] == 1 and blinkPulse_1)
	electrics.values['signal_RR_2'] = (electrics.values["signal_right_input"] == 1 and blinkPulse_2)
	electrics.values['signal_RR_3'] = (electrics.values["signal_right_input"] == 1 and blinkPulse_3)
	
	if electrics.values["signal_right_input"] == 0 and electrics.values["signal_left_input"] == 0 then
		blinkPulse_1 = 0  
		blinkPulse_2 = 0
		blinkPulse_3 = 0
		blinkTimer = 0
	end
	
	if electrics.values["rpm"] >= 3100 then
		electrics.values['tneedle'] = 1
	else
		electrics.values['tneedle'] = 0
	end
end

M.init = init
M.updateGFX = updateGFX

return M