#include "../../config/events.lua"
-- #include "../../config/platforms.lua" -- too heavy file for one simple registry check
#include "../helpers/entity.lua"

VIA_KEYPRESS = GetBoolParam("toggle_via_keypress", true)
ACTIVATION_SND = GetStringParam("activation_sound", "") -- MOD/snd/[FILE].ogg [volume]

function init()
	lights = FindLights("blink")
	veh = GetBodyVehicle(GetShapeBody(GetLightShape(lights[1])))
	intensities = {}
	for i = 1, #lights do
		local light = lights[i]
		local intensity = GetTagValue(light, "intensity")
		intensities[i] = intensity ~= "" and tonumber(intensity) or 1
	end

	state = not VIA_KEYPRESS and nil
    orig_state = state
	if ACTIVATION_SND~="" then
		local file, vol = ACTIVATION_SND:match("([%S]+)%s?([%d.]*)$")
		vol = tonumber(vol)
		snd_handle = LoadLoop("MOD/snd/" .. file .. ".ogg")
		snd_vol = 0
		max_vol = vol or 1
		pos = Vec()
		pos_update_framefreq = 10
		pos_update_count = 0
	end

    RegisterListenerTo(EVENTS.UPDATE_STATE, "UpdateState")
end

function UpdateState(data)
    if tonumber(data) ~= veh then return end

    toggle()
end

function toggle()
    if orig_state == nil then
        state = state==nil and true or nil
    else
        state = not state
    end

    if state == false then
        for i=1, #lights do
            SetLightIntensity(lights[i], 0)
        end
        if snd_vol then
            SetValue("snd_vol", 0, "cosine", 2.5)
        end
    elseif snd_vol then
        SetValue("snd_vol", max_vol, "cosine", 2.5)
    end
end

function tick(dt)
	if DISABLED then return end
	if VIA_KEYPRESS and GetPlayerVehicle()==veh and InputPressed(GetString("game.input.curdevice") == "gamepad" and "vehicle_lower" or "vehicle_raise") then
        toggle()
	end
	if state == false then return
    elseif state == nil and snd_vol == 0 then SetValue("snd_vol", max_vol, "cosine", 2.5) end

	local light
	for i=#lights, 1, -1 do
		local l = lights[i]
		if not IsHandleValid(l) or IsShapeBroken(GetLightShape(l)) or GetVehicleHealth(veh) <= 0 then
			SetLightIntensity(l, 0)
			table.remove(lights, i)
			if #lights == 0 then
                DISABLED = cEntity:EnqueueDeletion()
                return
            end
		else
			local intensity = intensities[i]
			local p = tonumber(GetTagValue(l, "blink"))
			local s = math.sin((GetTime()+i) * p)
			SetLightIntensity(l, s > 0 and intensity or 0)
		end
		if not light then light = l end
	end

	if light and snd_handle then
		if pos_update_count >= pos_update_framefreq then
			pos = GetLightTransform(light).pos
			pos_update_count = 0
		else
			pos_update_count = pos_update_count + 1
		end
	end

	if pos and snd_handle then
		PlayLoop(snd_handle, pos, snd_vol)
	end
end
