---@type pd_graphics_lib
local gfx <const> = playdate.graphics

local ThrowMeterHeight <const> = 50
local ThrowMeterLingerSec <const> = 1.5

local flickerTimer = gfx.animation.blinker.new(50, 50, true)
flickerTimer:start()

---@param x number
---@param y number
function throwMeter:draw(x, y)
    gfx.setLineWidth(1)
    gfx.drawRect(x, y, 14, ThrowMeterHeight)
    if self.lastReadThrow then
        local ratio = 1
        if not self.wasPerfect then
            ratio = (self.lastReadThrow - throwMeter.MinCharge) / (self.idealPower - throwMeter.MinCharge)
        end
        local height = ThrowMeterHeight * ratio
        gfx.fillRect(x + 2, y + ThrowMeterHeight - height, 10, height)
        -- TODO: Dither or bend if the user throws too hard
        -- Or maybe dither if it's too soft - bend if it's too hard
        if self.wasPerfect then
            PerfectPowerBg:draw(x - 11, y - 9)
            if flickerTimer.on then
                PerfectPowerFlickerLeft:draw(x - 11, y - 9)
            else
                PerfectPowerFlickerRight:draw(x - 11, y - 9)
            end
        end
    end
end

function throwMeter:drawNearFielder(fielder)
    if not fielder and not self.lastThrower then
        return
    end
    if fielder then
        if fielder ~= self.lastThrower then
            self.lastReadThrow = nil
        end
        self.lastThrower = fielder
        actionQueue:upsert("throwMeterLinger", 200 + ThrowMeterLingerSec * 1000, function()
            local dt = 0
            while dt < ThrowMeterLingerSec do
                dt = dt + coroutine.yield()
            end
            self.lastThrower = nil
        end)
    end
    self:draw(self.lastThrower.x - 25, self.lastThrower.y - 10)
end
