local cwd  = (...):gsub('%.player$', '') .. "."
local Parent = require(cwd .. "parent")
local Player = Parent:extend()

function Player:new(world, x, y, z, id)
  Player.super.new(self, world, "player", x, y, 0, 16, 12, 24, true)
  self:setGravity(480*2)

  self:setSprite("sonic", 8, 10)
  self:cloneSprite()

  self.guiborder = game.gui.newBorder(424, 20, 6)
  self.emblem     = love.graphics.newImage("assets/gui/emblem_speedster.png")
  self.status     = love.graphics.newImage("assets/gui/status_bar.png")

  self.action = "normal"
end

function Player:updateStart(dt)
  self.xfrc, self.yfrc = 480*3, 480*3

  if self.keys["up"].isDown and (self.action ~= "punching") then
    self.ysp = -160
  end
  if self.keys["down"].isDown and (self.action ~= "punching") then
    self.ysp =  160
  end
  if self.keys["left"].isDown and (self.action ~= "punching") then
    self.xsp = -160
  end
  if self.keys["right"].isDown and (self.action ~= "punching") then
    self.xsp =  160
  end

  if self.keys["A"].isDown and (self.onGround) and (self.action ~= "punching") then
    self.zsp = 280*1.33
  end

  if self.keys["B"].isPressed and (self.onGround) then
    self.action = "punching"
    --self.xsp = 0
    --self.ysp = 0

    if self:getCurrentAnimation() == "hit1" then
      self:changeAnimation("hit2", true)
    elseif self:getCurrentAnimation() == "hit2" then
      self:changeAnimation("hit3", true)
    elseif self:getCurrentAnimation() == "hit3" then
      --self:changeAnimation("hit1", true)
    else
      self:changeAnimation("hit1", true)
    end
  end
end

function Player:animationEnded(name)
  if (name == "hit1") or (name == "hit2") or (name == "hit3") then
    self.action = "normal"
  end
end

function Player:updateEnd(dt)
  self:setAnimation()
end

function Player:setAnimation()
  local gsp = utils.math.pointDistance(0, 0, self.xsp, self.ysp)
  self:setCustomSpeed(math.abs(gsp) / 12)
  self:setDirection(self.xsp)
  if (self.action == "punching") then
    --the animation system is already active
  else
    if (self.onGround) then
      if (math.abs(self.xsp) > 0) or (math.abs(self.ysp) > 0) then
        self:changeAnimation("walk", false)
      else
        self:changeAnimation("idle", false)
      end
    else
      if (self.zsp) > 0 then
        self:changeAnimation("jump", false)
      else
        self:changeAnimation("fall", false)
      end
    end
  end
end

function Player:setDirection(direction)
  direction = direction or 0
  if direction ~= 0 then
    direction = utils.math.sign(direction)
    self.direction = direction
    self:setSpriteScallingX(direction)
  end
end

function Player:getViewCenter()
  local x, y = Player.super.getViewCenter(self)
  return x, y-16
end

function Player:draw()
  Player.super.draw(self)
end

function Player:drawHUD(id)
  love.graphics.draw(self.guiborder, 424, 20, 0, -1, -1)
  love.graphics.draw(self.emblem, 8, 8, 0)
  love.graphics.draw(self.status, 24, 16, 0)
end

return Player
