FloatingText = {}
class('FloatingText').extends(playdate.graphics.sprite)

local floatFont = Graphics.font.new('assets/fonts/Mini Sans 2X')

local phrases = { "-1", "nice", "200", "dead", "done", "nice shot", "boom", "rip", "lol", "ez" }

function FloatingText.spawnCustom(x, y, text)
    local ft = FloatingText(x, y)
    ft.text = text
    local w = floatFont:getTextWidth(text) + 4
    ft:setSize(w, 16)
    ft:markDirty()
    return ft
end

function FloatingText:init(x, y)
    FloatingText.super.init(self)

    self.text = phrases[math.random(1, #phrases)]
    self.life = 0
    self.maxLife = 60
    self.driftX = math.random(-20, 20) / 10
    self.driftY = -math.random(10, 20) / 10

    local w = floatFont:getTextWidth(self.text) + 4
    self:setSize(w, 16)
    self:setCenter(0.5, 0.5)
    self:setZIndex(ZIndex.ui + 1)
    self:moveTo(x, y)
    self:add()
    self:markDirty()
end

function FloatingText:update()
    self.life = self.life + 1
    if self.life >= self.maxLife then
        self:remove()
        return
    end

    self:moveBy(self.driftX, self.driftY)
    self.driftY = self.driftY + 0.03
    self:markDirty()
end

function FloatingText:draw()
    local t = 1 - (self.life / self.maxLife)
    if t > 0.5 then
        floatFont:drawText(self.text, 2, 0)
    else
        local dither = playdate.graphics.image.kDitherTypeBayer4x4
        local img = Graphics.image.new(self.width, self.height)
        Graphics.pushContext(img)
        floatFont:drawText(self.text, 2, 0)
        Graphics.popContext()
        img:drawFaded(0, 0, t * 2, dither)
    end
end
