local slick = require("love_src.lib.slick")

local racer = require("love_src.src.entities.racing.racer")
local player = require("love_src.src.entities.shared.actor").load()

local mode = {}

local finish = {100, 100, 0}

local time = 0


local w, h = 800, 600

function mode:load()
  self.entities = {}
  self.level = {}
  self.world = slick.newWorld(w, h, {
    quadTreeX = 0,
    quadTreeY = 0
  })

  local new_racer = racer.load(player, finish)

  self.world:add(new_racer, 200, 500, slick.newCircleShape(0, 0, 16))

  table.insert(self.entities, new_racer)

  self.world:add(self.level, 0, 0, slick.newShapeGroup(
      -- Boxes surrounding the map
      slick.newRectangleShape(0, 0, w, 8), -- top
      slick.newRectangleShape(0, 0, 8, h), -- left
      slick.newRectangleShape(w - 8, 0, 8, h), -- right
      slick.newRectangleShape(0, h - 8, w, 8), -- bottom
      -- Triangles in corners
      slick.newPolygonShape({ 8, h - h / 8, w / 4, h - 8, 8, h - 8 }),
      slick.newPolygonShape({ w - w / 4, h, w - 8, h / 2, w - 8, h }),
      -- Convex shape
      slick.newPolygonMeshShape({ w / 2 + w / 4, h / 4, w / 2 + w / 4 + w / 8, h / 4 + h / 8, w / 2 + w / 4, h / 4 + h / 4, w / 2 + w / 4 + w / 16, h / 4 + h / 8 })
  ))
end

local function movePlayer(p, dt)
  local goalX, goalY = p.x + dt * p.velocityX, p.y + dt * p.velocityY
  p.x, p.y = world:move(p, goalX, goalY)
end

function mode:update(dt)
  for _,e in pairs(self.entities) do
    e:update(dt)

    -- local goalX, goalY = w / 2, -1000

    -- local actualX, actualY, collisions, count = self.world:move(e, goalX, goalY, function(item, other, shape, otherShape)
    --   return "slide"
    -- end)
    -- print(actualX, actualY)
    -- movePlayer(e, dt)
  end
  time = time + dt
end

function mode:draw()
  for _,e in pairs(self.entities) do
    e:draw()
  end
  slick.drawWorld(self.world)
  love.graphics.print(time, love.graphics.getWidth() / 2, love.graphics.getHeight()/ 2)
end

function mode:keyreleased(key, scancode)
end

function mode:keypressed(key, scancode, isrepeat)
end

function mode:mousereleased(x, y, button, istouch, presses)
end

return mode
