-- world2D.lua :: a basic 2D world based on bump2D.

--[[
  Copyright © 2019 Kazhnuz

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]

local cwd   = (...):gsub('%.world2D$', '') .. "."

local BaseWorld = require(cwd .. "baseworld")
local World2D   = BaseWorld:extend()

local Bump  = require(cwd .. "libs.bump")
local CameraSystem  = require(cwd .. "camera")

function World2D:new(scene, actorlist, mapfile, maptype)
  World2D.super.new(self, scene, actorlist, mapfile, maptype)
end

-- ACTORS FUNCTIONS
-- Add support for bodies in Actor functions

function World2D:initActors()
  self.currentCreationID  = 0
  self.actors = {}
  self.bodies = Bump.newWorld(50)
end

function World2D:registerActor(actor)
  World2D.super.registerActor(self, actor)
end

function World2D:moveActor(actor, x, y, filter)
  return self.bodies:move(actor.mainHitbox, x, y, filter)
end

function World2D:getActorsInRect(x, y, w, h)
  local bodies = self.bodies:queryRect(x, y, w, h)
  local returnquery = {}

  for i,body in ipairs(bodies) do
    if (body.isMainHitBox) then
      table.insert(returnquery, body.owner)
    end
  end

  return returnquery
end

-- BODIES MANAGEMENT FUNCTIONS
-- Basic function to handle bodies. Wrappers around Bump2D functions

function World2D:registerBody(body)
  return self.bodies:add(body, body.x, body.y, body.w, body.h)
end

function World2D:updateBody(body)
  return self.bodies:update(body, body.x, body.y, body.w, body.h)
end

function World2D:removeBody(body)
  return self.bodies:remove(body)
end

function World2D:checkCollision(body, x, y, filter)
  return self.bodies:check(body, x, y, filter)
end

function World2D:getBodiesInRect(x, y, w, h)
  return self.bodies:queryRect(x, y, w, h)
end

return World2D
