Granade = {}
class('Granade').extends(NobleSprite)

function Granade:init(x, y)
    Granade.super.init(self)
    
    self.initialRadius = 10
    self.currentRadius = self.initialRadius
    self.shrinkRate = 0.2

    local random = math.random(1, 4)
    self.boomSound = playdate.sound.fileplayer.new("assets/audio/boom" .. random)
    self.boomSound:setVolume(0.5)
    
    self.isActive = true

    self.randomMovementTimer = 0
    self.randomXVelocity = 0
    self.randomYVelocity = 0

    local size = self.initialRadius * 2
    self.spriteSize = size
    self:setSize(size, size)
    self:moveTo(x, y)
    self:setZIndex(10)
    self:setTag(154)
    self:setCenter(0.5, 0.5)
    self:setGroups(CollideGroups.granade)
    self:setCollidesWithGroups({
        CollideGroups.enemy
    })
    self:setCollideRect(0, 0, self:getSize())

    print("Granade init")
    print(self.x, self.y)
    self:add(x, y)
    self:markDirty()
end

function Granade:update()
    if self.isActive then 
        if BomberScene.instance then
            self:moveBy(0, BomberScene.instance.scrollSpeed - 0.2)
            
            self.randomMovementTimer = self.randomMovementTimer + 1
            
            if self.randomMovementTimer >= 10 then
                self.randomMovementTimer = 0
                self.randomXVelocity = math.random(-50, 50) / 100
                self.randomYVelocity = math.random(-5, 10) / 100
            end
            
            self:moveBy(self.randomXVelocity, self.randomYVelocity)
        end
        
        self.currentRadius = self.currentRadius - self.shrinkRate
    
        if self.currentRadius <= 0 then
            print("Granade deactivated")
            self.isActive = false
            local particleB = ParticlePoly(self.x, self.y)
            particleB:setThickness(1)
            particleB:setAngular(-5, 5122)
            particleB:setSize(1, 2)
            particleB:setSpeed(1, 20)
            particleB:setMode(Particles.modes.STAY)
            particleB:setBounds(0, 0, 400, 240)
            particleB:setColour(Graphics.kColorXOR)
            particleB:add(20)
            self.boomSound:play(1)
            screenShake(1000, 5)
            SmallBoom()
            ExplosionMark(self.x, self.y)
            
            self:remove()
        end
    end
    self:markDirty()
end

function Granade:draw()
    local centerX = self.spriteSize / 2
    local centerY = self.spriteSize / 2
    playdate.graphics.fillCircleAtPoint(centerX, centerY, self.currentRadius)
end