local animator = require '../engine/animator'

Gridwalker = class('Gridwalker')

Gridwalker.speed = 2

function Gridwalker:init(objectinfo, world)
    self.info = objectinfo
    self.world = world
    self.animator = Animator(self.info.image:getWidth(), self.info.image:getHeight())
    self.animation = self.animator[self.info.pose]
    self.animation:pauseAtStart()
end

function Gridwalker:sendMovement(key)
    if self[key] ~= nil then
        self[key](self)
    end
end

function Gridwalker:stopAnimation()
  self.animation:pauseAtStart()
end

function Gridwalker:startAnimation(animationName)
  self.animation = self.animator[animationName]
  self.animation:resume()
end

function Gridwalker:up()
  self.animation = self.animator.walk_up
  self:move(0, - self.speed)
end

function Gridwalker:down()
  self.animation = self.animator.walk_down
  self:move(0, self.speed)
end

function Gridwalker:right()
  self.animation = self.animator.walk_right
  self:move(self.speed, 0)
end

function Gridwalker:left()
  self.animation = self.animator.walk_left
  self:move(- self.speed, 0)
end

function Gridwalker:move(x, y)
    self.animation:resume()

    local goalX, goalY = self.info.collision.x + x, self.info.collision.y + y
    local actualX, actualY, cols, len = self.world:move(self.info.collision, goalX, goalY)

    if len == 0 then
        self.info.x = self.info.x + x
        self.info.y = self.info.y + y

        if self.info.collision then
            self.info.collision.x = self.info.collision.x + x
            self.info.collision.y = self.info.collision.y + y
            self.world:update(self.info.collision, self.info.collision.x, self.info.collision.y)
        end
    end
end

function Gridwalker:draw()
    self.animation:draw(self.info.image, self.info.x, self.info.y)
end

return Gridwalker
