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

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

    self.crateSize = 20
    self:setSize(self.crateSize, self.crateSize)
    self:setCenter(0.5, 0.5)
    self:setZIndex(ZIndex.props)
    self:setGroups(CollideGroups.props)
    self:setCollidesWithGroups({ CollideGroups.granade })
    self:setCollideRect(0, 0, self.crateSize, self.crateSize)
    self:setTag(Tags.ammoCrate)

    self.removed = false
    self.bonusGrenades = 3

    self:moveTo(x, y)
    self:add()
    self:markDirty()
end

function AmmoCrate:update()
    if self.removed then return end
    if not BomberScene.instance then return end

    self:moveBy(0, BomberScene.instance.scrollSpeed)

    local _, _, collisions, count = self:checkCollisions(self.x, self.y)
    if count > 0 then
        for i, collision in ipairs(collisions) do
            if collision.other:getTag() == Tags.granade and collision.other.currentRadius <= 0.05 then
                self:pickup()
                return
            end
        end
    end

    if self.y > 260 then
        self.removed = true
        self:remove()
    end
end

function AmmoCrate:pickup()
    self.removed = true
    BomberScene.availableGrenades = BomberScene.availableGrenades + self.bonusGrenades

    local particle = ParticlePoly(self.x, self.y)
    particle:setThickness(1)
    particle:setSize(1, 2)
    particle:setSpeed(1, 5)
    particle:setColour(Graphics.kColorXOR)
    particle:add(8)

    self:remove()
end

function AmmoCrate:draw()
    local s = self.crateSize
    -- Box outline
    playdate.graphics.drawRect(0, 0, s, s)
    -- Cross pattern
    playdate.graphics.drawLine(0, 0, s, s)
    playdate.graphics.drawLine(s, 0, 0, s)
    -- Inner + symbol
    local mid = s / 2
    playdate.graphics.drawLine(mid - 3, mid, mid + 3, mid)
    playdate.graphics.drawLine(mid, mid - 3, mid, mid + 3)
end
