import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/timer"
import "CoreLibs/crank"

import "pixie"
import "ball"

local gfx <const> = playdate.graphics

local paddle = nil
local boundary = nil
local ball = nil

local ballVector = {}
local ballSpeed = 3

local gameOver = false
local gameOverText <const> = "Game Over!\nPress 'A' to play again."

function setup()
   levelTimer()
   
   paddle = Pixie(6, 80, gfx.kColorWhite, 5, 120)
   paddle:add()
   boundary = Pixie(2, 240, gfx.kColorClear)
   boundary:add()
   ball = Ball(6, 6, gfx.kColorWhite, 200, 120)
   ball:add()
   
   local backgroundImage = gfx.image.new(400, 240, gfx.kColorBlack)
   gfx.sprite.setBackgroundDrawingCallback(
      function(x, y, width, height)
         backgroundImage:draw(0, 0)
         if gameOver then
            gfx.setColor(gfx.kColorWhite)
            gfx.fillRect(0, 80, 400, 80)
            local level = ball.speed - 2
            playdate.graphics.drawTextAligned("Game Over!\nYou reached level " ..
                                              level ..
                                              "\nPress 'A' to play again.", 200, 90, kTextAlignment.center)
         end
      end
   )
end

function levelTimer() 
   playdate.timer.new(10000,
      function()
         ball:levelUp()
         levelTimer()
      end
   )
end

function playdate.update()
   gfx.clear()
   if gameOver then
      if playdate.buttonJustPressed(playdate.kButtonA) then
         paddle:remove()
         boundary:remove()
         ball:remove()
         playdate.file.run("main.pdz")
      end
   else
      -- Check collisions
      local collisions = ball:overlappingSprites()
      for i = 1, #collisions do
         local collision = collisions[i]
         if collision == paddle then
            redirectBall()
         end
         if collision == boundary then
            gameOver = true
         end
      end

      -- Handle movement
      movePaddle(playdate.getCrankTicks(80))
      ball:move()
      playdate.timer.updateTimers()
   end
   gfx.sprite.update()
end

function redirectBall()
   ball:setDirection(1)
end

function movePaddle(ticks)
   if ticks == 0 then return end
   paddle:moveBy(0, ticks*-5)
end

setup()