player_health = {}

local PATH_BACKGROUND_IMG = "../../ui/hud/health/health_back.png"
local PATH_CELLS_IMG = "../../ui/hud/health/health_cell.png"
local PATH_HEALTH_IMG = "../../ui/hud/health/health_bar.png"

local player_veh

function player_health:Init()
    player_veh = GetPlayerVehicle()

    colorGood_R, colorGood_G, colorGood_B         = 1, 1, 1
	colorBroken_R, colorBroken_G, colorBroken_B   = 1, 0.36, 0.24
    healthScale         = 1
    timeToPuls          = 0.4
end

function player_health:Draw(dt)
    UiPush()
        UiTranslate(UiCenter(), UiHeight()-53)
        UiAlign("center bottom")
        UiScale(1.2)
        if player_veh ~= 0 then
            self:drawHealth(GetVehicleHealth(player_veh))
        end
    UiPop()
end

function player_health:drawHealth(percentLife)
    local w, h = UiGetImageSize(PATH_BACKGROUND_IMG)
    local needChangeColor = percentLife <= 0.75
    UiPush()
        UiWindow(w, h)
        UiTranslate(UiCenter(), UiMiddle())
        UiAlign("center middle")

        local wHP, hHP = UiGetImageSize(PATH_HEALTH_IMG)
        local r, g, b
        if needChangeColor then
            local healthColorLerp = 1
            local healthColorLerpG = 1
            local healthColorLerpB = 1
            healthToBrokenColor = percentLife - 0.25
            if healthToBrokenColor <= 0 then
                r, g, b = colorBroken_R, colorBroken_G, colorBroken_B
                if healthScale == 1 then
                    SetValue("healthScale", 1.25, "easein", timeToPuls)
                elseif healthScale == 1.25 then
                    SetValue("healthScale", 1, "easeout", timeToPuls)
                end
            else
                healthColorLerp = healthToBrokenColor / 0.5
                healthColorLerpG = math:Lerp(colorBroken_G, colorGood_G, healthColorLerp)
                healthColorLerpB = math:Lerp(colorBroken_B, colorGood_B, healthColorLerp)
                r, g, b = colorBroken_R, healthColorLerpG, healthColorLerpB
            end
        else
            r, g, b = colorGood_R, colorGood_G, colorGood_B
        end

        UiScale(healthScale)
        UiImage(PATH_BACKGROUND_IMG)
        UiPush()
            UiTranslate(-UiCenter(), 0)
            UiAlign("left middle")
            UiColor(r, g, b)
            UiImage(PATH_HEALTH_IMG, 0, 0, wHP*percentLife, hHP)
        UiPop()
        UiImage(PATH_CELLS_IMG)
    UiPop()
    return w, h
end

function player_health:drawEnemyHealth(percentLife)
    local w, h = UiGetImageSize(PATH_BACKGROUND_IMG)
    UiPush()
        UiWindow(w, h)
        UiTranslate(0, UiMiddle())
        UiAlign("left middle")

        UiImage(PATH_BACKGROUND_IMG)

        UiPush()
            local wHP, hHP = UiGetImageSize(PATH_HEALTH_IMG)
            UiImage(PATH_HEALTH_IMG, 0, 0, wHP*percentLife, hHP)
        UiPop()

        UiImage(PATH_CELLS_IMG)
    UiPop()
    return w, h
end
