#include "../../config/constants.lua"

lap_time = {}

local REGISTRY_BEST_LAP = 'level.time.best'
local REGISTRY_TIME = 'level.time'
local maxWidth = 0

function lap_time:findMaxWidth()
    UiFont("bold.ttf", 22)
    margins = 42
    wTime = 0
    UiPush()
        UiFont(DIGIT_FONT_BOLD, 22)
        wTime = UiGetTextSize("00:00.000") + 4
    UiPop()
    local w1 = UiGetTextSize(GetTranslatedStringByKey("UI_TIME"))
    local w2 = UiGetTextSize(GetTranslatedStringByKey("UI_LAP_TIME"))
    local w3 = UiGetTextSize(GetTranslatedStringByKey("UI_BEST_TIME"))
    maxWidth = math.max(w1, w2, w3) + margins + wTime
end

function lap_time:Draw(dt)
    -- if maxWidth == 0 then
    --     self:findMaxWidth()
    -- end
    self:findMaxWidth()

    UiPush()
        UiTranslate(24, 104)

        local lap_start_time = 0
        for i = 0, GetInt("level.playerlap") do
            lap_start_time = lap_start_time + GetFloat('level.time.lap' .. i)
        end

        local time, frac = math.modf(GetFloat(REGISTRY_TIME))
        self:DrawRow("loc@UI_TIME", ("%02d:%02d.%03d"):format(time/60, time%60, frac*1000))

        UiTranslate(0, 35)
        if time >= 0 and frac > 0 then
            time, frac = math.modf(GetTime() - lap_start_time)
        else
            time, frac = 0, 0
        end
        self:DrawRow("loc@UI_LAP_TIME", ("%02d:%02d.%03d"):format(time/60, time%60, frac*1000))

        UiTranslate(0, 35)
        time, frac = math.modf(GetFloat(REGISTRY_BEST_LAP))
        self:DrawRow("loc@UI_BEST_TIME", ("%02d:%02d.%03d"):format(time/60, time%60, frac*1000))
    UiPop()
end

function lap_time:DrawRow(title, time)
    local width = maxWidth
    local height = 31
    UiPush()
        UiWindow(width, height)
        UiAlign("left top")

        PAGE_COMPONENTS:drawRoundedColorRect(width, height, 6, 0, 0, 0, 0.5)
        UiTranslate(8, UiMiddle())
        self:DrawTitle(title)
        UiTranslate(UiWidth() - wTime - 16, 0)
        self:DrawValue(time)
    UiPop()
end

function lap_time:DrawTitle(name)
    UiPush()
        UiFont("bold.ttf", 22)
        UiAlign("left middle")
        UiTextUniformHeight(true)
        UiText(name)
    UiPop()
end

function lap_time:DrawValue(value)
    UiPush()
        UiFont(DIGIT_FONT_BOLD, 22)
        UiAlign("left middle")
        UiWindow(wTime, 31)
        UiTranslate(0, UiMiddle())
        UiAlign("left middle")
        UiTextUniformHeight(true)
        UiText(value)
    UiPop()
end
