#include "../config/music.lua"
#include "helpers/entity.lua"

pEnableByDefault = GetBoolParam("enable", false)

function init()
	--Find handle to radio
	radio = FindShape("toggle")
    speakers = FindShapes("speaker")

	--Make sure the light is turned off and make interactable
	SetShapeEmissiveScale(radio, 0)
	for k,speaker in pairs(speakers) do
		SetShapeEmissiveScale(speaker, 0)
	end

	--Load click sound and music from game assets
	clickSound = LoadSound("clickdown.ogg")
	musicLoop = LoadLoop(MUSIC.lobby)

    isStoreSpeaker = GetTagValue(speakers[1], "speaker") == "store"
    pcScreen = nil

    on = pEnableByDefault

    if on then
        enableRadio()
    else
        disableRadio()
    end
end

function enableRadio()
    on = true
    for k,speaker in pairs(speakers) do
        SetShapeEmissiveScale(speaker, 1)
    end
    SetTag(radio, "interact", "loc@TURN_OFF")
end

function disableRadio()
    on = false
    for k,speaker in pairs(speakers) do
        SetShapeEmissiveScale(speaker, 0)
    end
    SetTag(radio, "interact", "loc@TURN_ON")
end

function tick(dt)
    if on == nil then return end

	--If radio is broken it should not be interactable and not function
	if not IsHandleValid(radio) or IsShapeBroken(radio) then
		RemoveTag(radio, "interact")
        cEntity:EnqueueDeletion()
        on = nil
		return
	end
    if not pcScreen then pcScreen = GetInt("level.screen") end

	--Turn on/off radio
	if GetPlayerInteractShape() == radio and InputPressed("interact") then
		PlaySound(clickSound)
		if on then
            disableRadio()
		else
			enableRadio()
		end
	end

    -- start delay, because sometimes its sound plays at player location ignoring below conditions
    if GetTime() < 0.5 then
        return
    end

	--If radio is on, play music at the world position
	if on and not GetBool("cinematic.is_credits") and GetString("level.state") ~= "win" then
        local in_store = GetString("level.page") == "store"
        local is_using_pc = not in_store and GetPlayerScreen() == pcScreen and pcScreen > 0
        for k,speaker in pairs(speakers) do
            if IsShapeBroken(speaker) then
                speakers[k] = nil
            else
                local sound_2d = (not isStoreSpeaker and is_using_pc) or (isStoreSpeaker and in_store)
                local pos = sound_2d and GetCameraTransform().pos or GetShapeWorldTransform(speaker).pos
                PlayLoop(musicLoop, pos)
                if sound_2d then
                    break -- playing only once, no need to spam loop from all speakers
                end
            end
        end
	end
end
