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

local Hitbox  = require(cwd .. "utils.hitbox3D")
local Boxes   = require(cwd .. "utils.boxes")

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

function Actor3D:new(world, type, x, y, z, w, h, d, isSolid)
  Actor3D.super.new(self, world, type, x, y, z, w, h, d, isSolid)
  self:initHitboxes()
  self.world:registerShape(self)
  self.boxes = Boxes
  self.doCastShadows = true
end

function Actor3D:destroy()
  self:removeOldShadowTargets()
  if self.box ~= nil then
    self.world:removeTerrain(self)
  end
  self.world:removeActor(self)
  self.mainHitbox:destroy()
  self.world:removeShape(self)
  self.isDestroyed = true
end

-- PHYSICS FUNCTIONS
-- Handle movement and collisions.

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

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

  -- 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 Actor3D:changeSpeedToCollisionNormal(normal)
  local xsp, ysp, zsp = self.xsp, self.ysp, self.zsp
  local nx, ny, nz = normal.x, normal.y, normal.z

  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

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

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

function Actor3D:move(dx, dy, dz)
  local cols, colNumber = {}, 0
  local oldx, oldy, oldz = self.x, self.y, self.z
  if (self.isDestroyed == false) then
    self.x, self.y, self.z, cols, colNumber = self.mainHitbox:checkCollision(dx, dy, dz, self.filter)
    self.mainHitbox:updatePosition()
    self.world:updateShape(self)
  end

  if (oldx ~= self.x) or (oldy ~= self.y) or (oldz ~= self.z) or (self.shadowTargetsPrevious == nil) then
    if (self.doCastShadows) then
      self:castShadow()
    end
  end

  return self.x, self.y, self.z, cols, colNumber
end

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

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

function Actor3D:applyGravity(dt)
  local grav = self.grav * -1
  self.zsp = self.zsp + (grav * dt)

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

function Actor3D:checkGround()
  local dx, dy, dz = self.x, self.y, self.z - utils.math.sign(self.grav)
  local newx, newy, newz, cols, colNumber = self:checkCollision(dx, dy, dz)
  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.z == utils.math.sign(self.grav) then self.onGround = true end
      end
    end
  end
end

-- COORDINATE/MOVEMENT FUNCTIONS
-- Handle coordinate

function Actor3D:getViewCenter()
  local x, y, z = self:getCenter()
  return x, y - (self.d/2)
end

-- HITBOXES FUNCTIONS
-- Functions related to actor hitboxes

function Actor3D:addHitboxFromFrameData(framedata, animationID, frameID, hitboxID)
  local sx, sy = self:getSpriteScalling()
  local type  = framedata[1]
  local ox    = framedata[2]
  local oy    = framedata[3]
  local oz    = framedata[4]
  local w     = framedata[5]
  local h     = framedata[6]
  local d     = framedata[7]
  local isSolid = framedata[8] 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
    oz = self.d - oz - d
  end

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

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

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

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

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

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

    return x, y, z, cols, colNumber
end

-- SHADOW FUNCTIONS
-- Handle everything related to shadow

function Actor3D:castShadow()
  local shadowTargets = self.world:getTerrainInRect(self.x, self.y, self.w, self.d)
  -- initialize the shadowTargetsPrevious variable if it doesn't exist
  if (self.shadowTargetsPrevious == nil) then
    self.shadowTargetsPrevious = {}
  end

  for i, target in ipairs(shadowTargets) do
    -- We test if the actor is below the current actor
    if (target ~= self) and (target.box ~= nil) then

      if (target.z + target.d <= self.z + self.d) then
        -- Remove the target of the list of item targeted last update,
        -- in order to only have object no longer shadowed after the
        -- end of the loop
        for j, oldtarget in ipairs(self.shadowTargetsPrevious) do
          if (target == oldtarget) then
            table.remove(self.shadowTargetsPrevious, j)
          end
        end

        -- We update the shadow source
        local x, y = math.floor(self.x - target.x), math.floor(self.y - target.y)
        target.box:setShadowSource(self, x, y)
      end

    end

  end

  -- At this point, if a target is still in the shadowTargetsPrevious list,
  -- it mean that it's not shadowed. So we can simply remove the shadow.
  self:removeOldShadowTargets()

  self.shadowTargetsPrevious = shadowTargets
end

function Actor3D:removeOldShadowTargets()
  if (self.shadowTargetsPrevious ~= nil) then
    for i, target in ipairs(self.shadowTargetsPrevious) do
      if (target.box ~= nil) then
        target.box:removeShadowSource(self)
      end
    end
  end
end

function Actor3D:redrawShadowCanvas()
  if (self.box ~= nil) then
    self.box:redrawShadowCanvas()
  end
end

-- DRAW FUNCTIONS
-- Draw the actors.

function Actor3D:drawShadow(x, y)
  love.graphics.setColor(0, 0, 0, 1)
  love.graphics.rectangle("fill", x, y, self.w, self.h)
  utils.graphics.resetColor()
end

function Actor3D:getShape()
  return (self.x), (self.y - self.z - self.d), self.w, (self.h + self.d)
end

function Actor3D:draw()
  self:drawStart()
  if (self.box ~= nil) then
    self.box:draw(self.x, self.y, self.z)
  else
    local x, y = math.floor(self.x), math.floor(self.y - self.z - self.d + (self.h/2))
    self:drawSprite(x, y)
  end
  self:drawEnd()
end

return Actor3D
