#include "../helpers/mathfr.lua"

player_names = {}

local FONT = "bold.ttf"

local max_distance = 100
local car_parameters = {}

local player_veh
local alive_players

local sort, tremove = table.sort, table.remove
local drawHealth = player_health.drawEnemyHealth

function player_names:Init()
    player_veh      = GetPlayerVehicle()
    alive_players   = ListKeys("level.players")
end

function player_names:Draw(dt)
    car_parameters = {}
    local cam = GetCameraTransform()

    for i = #alive_players, 1, -1 do repeat
        local index = alive_players[i]
        local handle = GetInt("level.players." .. index)
        if handle == player_veh or not IsHandleValid(handle) then tremove(alive_players, i) break end

        local car_health = GetVehicleHealth(handle)
        if car_health <= 0 then tremove(alive_players, i) break end

        local vehicle_pos = cRegistry:GetTransformPlayer(index).pos
        -- local g = _G["gTransform" .. i].pos
        -- local vehicle_pos = GetVehicleTransform(handle).pos
        local z_diff = TransformToLocalPoint(cam, vehicle_pos)[3]
        if z_diff > 0 or z_diff <= -100 then break end

        local x_screen, y_screen, dist_screen = UiWorldToPixel(vehicle_pos)
        if dist_screen <= 1 then break end

        car_parameters[#car_parameters+1] = {
            car_handle = handle,
            car_place = GetInt("level.players." .. index .. ".place"),
            car_name = GetString("level.players." .. index .. ".name"),
            car_health = car_health,
            vehicle_pos = vehicle_pos,
            player_dist = -z_diff,
            screen_dist = dist_screen,
            screen_x = x_screen,
            screen_y = y_screen,
        }
    until true end

    sort(car_parameters, function(a, b) return a.screen_dist < b.screen_dist end)

    for i = 1, #car_parameters do
        local v = car_parameters[i]
        local x_screen = v.screen_x
        local y_screen = v.screen_y
        local dist_screen = v.screen_dist

        local scale = 1 - v.player_dist/max_distance
        UiPush()
            UiTranslate(x_screen, y_screen - 2000/dist_screen)
            UiScale(scale)
            self:drawName(v.car_place, v.car_name)

            local vehicle_health = v.car_health
            UiScale(1/scale)
            UiTranslate(0, 5)
            local healthScale = math:Clamp(scale * 0.35, 0.05, 0.35)
            UiScale(healthScale)
            if scale < 0.5 then
                UiColor(1, 1, 1, scale * 2)
            end
            local _, _ = drawHealth(player_health, vehicle_health)
        UiPop()
    end
end

function player_names:drawName(place_index, car_name)
    UiFont(FONT, 28)
    UiAlign("center")
    UiText(place_index .. ". " .. GetTranslatedStringByKey(car_name))
end
