#include "../config/events.lua"

-- Transform of every player, written in registry
-- (player index matching level.players index, "player" refers to player vehicle transform)
-- i.e.:
--  transform.6.pos
--  transform.6.rot

local alive_players

function init()
    RegisterListenerTo(EVENTS.STATS_FILLED, "OnStatsFilled")
end

function OnStatsFilled()
    alive_players = ListKeys("level.players")
    UnregisterListener(EVENTS.STATS_FILLED, "OnStatsFilled")
end

function draw(dt)
    if not alive_players then return end

    local player_veh = GetPlayerVehicle()
    for i = #alive_players, 1, -1 do
        local index = alive_players[i]
        local player_path = "transform." .. index
        local handle = GetInt("level.players." .. index)
        if IsHandleValid(handle) then
            local tr = GetVehicleTransform(handle)
            WriteRegistryInfo(tr, player_path)
            -- if handle == player_veh then WriteRegistryInfo(tr, "transform.player") end
        else
            ClearKey(player_path)
            table.remove(alive_players, i)
        end
    end
end

function WriteRegistryInfo(tr, path)
    SetColor(path .. ".pos", unpack(tr.pos))
    SetColor(path .. ".rot", unpack(tr.rot))
end
