-- actor2D.lua :: the implementation of a 2D actor. It contain every element
-- needed to create your own 2D actors.

--[[
  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('%.actor2D$', '') .. "."
local BaseActor = require(cwd .. "baseactor")
local Actor2D = BaseActor:extend()

local Hitbox  = require(cwd .. "utils.hitbox2D")

-- INIT FUNCTIONS
-- Initialise the actor and its base functions

function Actor2D:new(world, type, x, y, w, h, isSolid)
  Actor2D.super.new(self, world, type, x, y, 0, w, h, 0, isSolid)
  self:initHitboxes()
end

function Actor2D:destroy()
  self.world:removeActor(self)
  self.mainHitbox:destroy()
  self.isDestroyed = true
end

-- PHYSICS FUNCTIONS
-- Handle movement and collisions.

function Actor2D:autoMove(dt)
  self:updateHitboxes()
  self.onGround = false
  self:applyGravity(dt)

  local dx, dy = self:getFuturePosition(dt)
  local newx, newy, cols, colNumber = self:move(dx, dy)

  -- apply after the movement the friction, until the player stop
  -- note: the friction is applied according to the delta time,
  -- thus the friction should be how much speed is substracted in 1 second

  self:solveAllCollisions(cols)

  self:applyFriction(dt)
end

function Actor2D:changeSpeedToCollisionNormal(normal)
  local xsp, ysp = self.xsp, self.ysp
  local nx, ny = normal.x, normal.y

  if (nx < 0 and xsp > 0) or (nx > 0 and xsp < 0) then
    xsp = -xsp * self.bounceFactor
  end

  if (ny < 0 and ysp > 0) or (ny > 0 and ysp < 0) then
    ysp = -ysp * self.bounceFactor
  end

  self.xsp, self.ysp = xsp, ysp
end

function Actor2D:move(dx, dy)
  local cols, colNumber = {}, 0
  if (self.isDestroyed == false) then
    self.x, self.y, cols, colNumber = self.mainHitbox:checkCollision(dx, dy, self.filter)
    self.mainHitbox:updatePosition()
  end
  return self.x, self.y, cols, colNumber
end

function Actor2D:checkCollision(dx, dy)
  local x, y, cols, colNumber = dx, dy, {}, 0
  if (self.isDestroyed == false) then
    x, y, cols, colNumber = self.mainHitbox:checkCollision(dx, dy, self.filter)
  end
  return self.x, self.y, cols, colNumber
end

-- GRAVITY SYSTEM FUNCTIONS
-- All functions related to gravity

function Actor2D:applyGravity(dt)
  self.ysp = self.ysp + self.grav * dt

  if utils.math.sign(self.ysp) == utils.math.sign(self.grav) then
    self:checkGround( )
  end
end

function Actor2D:checkGround()
  local dx, dy = self.x, self.y + utils.math.sign(self.grav)
  local newx, newy, cols, colNumber = self:checkCollision(dx, dy)

  for i, col in ipairs(cols) do
    if (col.type == "touch") or (col.type == "bounce") or (col.type == "slide") then
      if not (self.grav == 0) then
        if col.normal.y ~= utils.math.sign(self.grav) then self.onGround = true end
      end
    end
  end
end

-- COORDINATE/MOVEMENT FUNCTIONS
-- Handle coordinate

function Actor2D:getViewCenter()
  local x, y = self:getCenter()
  return x, y
end

-- HITBOXES FUNCTIONS
-- Functions related to actor hitboxes

function Actor2D:addHitboxFromFrameData(framedata, animationID, frameID, hitboxID)
  local sx, sy = self:getSpriteScalling()
  local type  = framedata[1]
  local ox    = framedata[2]
  local oy    = framedata[3]
  local w     = framedata[4]
  local h     = framedata[5]
  local isSolid = framedata[6] or false
  local anim  = animationID or "null"
  local frame = frameID or 0
  local id    = hitboxID or 0
  if (sx < 0) then
    ox = self.w - ox - w
  end
  if (sy < 0) then
    oy = self.h - oy - h
  end

  if (type == "main") then
    self.mainHitbox:modify(ox, oy, w, h)
  else
    local hitboxName = anim .. frame .. type .. id
    self:addHitbox(hitboxName, type, ox, oy, w, h, isSolid)
    return hitboxName
  end
end

function Actor2D:initMainHitbox()
  self.mainHitbox = Hitbox(self, self.type, 0, 0, self.w, self.h, self.isSolid)
  self.mainHitbox:advertiseAsMainHitbox()
end

function Actor2D:addHitbox(name, type, ox, oy, w, h, isSolid)
  if (self.hitboxes[name] ~= nil) then
    core.debug:warning("actor2D", "the hitbox " .. name .. " already exists")
  else
    local hitbox = Hitbox(self, type, ox, oy, w, h, isSolid)
    self.hitboxes[name] = hitbox
    return hitbox
  end
end

function Actor2D:checkHitboxCollisions(name, filter)
  self:checkHitboxCollisionsAtPoint(name, self.x, self.y, filter)
end

function Actor2D:checkHitboxCollisionsAtPoint(name, dx, dy, filter)
    local x, y, cols, colNumber = dx, dy, {}, 0
    local filter = filter or self.filter
    if (self.isDestroyed == false) and (self.hitboxes[name] ~= nil) then
      x, y, cols, colNumber = self.hitboxes[name]:checkCollision(dx, dy, filter)
      local type = self.hitboxes[name].type

      for i, col in ipairs(cols) do
        self:hitboxResponse(name, type, col)
      end
    end

    return x, y, cols, colNumber
end

-- DRAW FUNCTIONS
-- Draw the actors.

function Actor2D:getShape()
  return (self.x), (self.y), self.w, (self.h)
end

function Actor2D:draw()
  self:drawStart()
  local x, y = math.floor(self.x), math.floor(self.y)
  self:drawSprite(x, y)
  self:drawEnd()
end

return Actor2D
