local Sprite = Object:extend()

-- SPRITES FUNCTIONS
-- Handle the sprite of the actor

function Sprite:new(owner, spritename, ox, oy)
  self.owner = owner
  self.assets = self.owner.assets
  self.name    = spritename or nil
  self.ox      = ox or 0
  self.oy      = oy or 0
  self.sx      = 1
  self.sy      = 1
  self.exist   = (spritename ~= nil)
  self.spriteClone   = nil
end

function Sprite:clone()
  if self.name ~= nil then
    local baseSprite = self.assets:getWithType(self.name, "sprite")
    self.spriteClone = baseSprite:clone()
    self.spriteClone:setCallbackTarget(self.owner)
  end
end

function Sprite:isCloned()
  return (self.spriteClone == nil)
end

function Sprite:changeAnimation(animation, restart)
  if (self:isCloned()) then
    self.assets.sprites[self.name]:changeAnimation(animation, restart)
  else
    self.spriteClone:changeAnimation(animation, restart)
  end
end

function Sprite:setCustomSpeed(customSpeed)
  if (self:isCloned()) then
    self.assets.sprites[self.name]:setCustomSpeed(customSpeed)
  else
    self.spriteClone:setCustomSpeed(customSpeed)
  end
end

function Sprite:update(dt)
  if (self.spriteClone ~= nil) then
    self.spriteClone:update(dt)
  end
end

function Sprite:setScalling(sx, sy)
  if (sx ~= nil) then
    self.sx = sx
  end

  if (sy ~= nil) then
    self.sy = sy
  end
end

function Sprite:getCurrentAnimation()
  if (self:isCloned()) then
    return self.assets.sprites[self.name]:getCurrentAnimation()
  else
    return self.spriteClone:getCurrentAnimation()
  end
end


function Sprite:getScalling()
  return self.sx, self.sy
end

function Sprite:getFrame()
  if (self.name ~= nil) then
    if (self.spriteClone ~= nil) then
      return self.spriteClone:getFrame()
    else
      return self.assets.sprites[self.name]:getFrame()
    end
  end
end

function Sprite:getRelativeFrame()
  if (self.name ~= nil) then
    if (self.spriteClone ~= nil) then
      return self.spriteClone:getRelativeFrame()
    else
      return self.assets.sprites[self.name]:getRelativeFrame()
    end
  end
end

function Sprite:getAnimationDuration()
  if (self.name ~= nil) then
    if (self.spriteClone ~= nil) then
      return self.spriteClone:getAnimationDuration()
    else
      return self.assets.sprites[self.name]:getAnimationDuration()
    end
  end
end

function Sprite:draw(x, y, r, sx, sy, ox, oy, kx, ky)
  if (self.name ~= nil) then
    local x = x + self.ox
    local y = y + self.oy
    local sx = sx or self.sx
    local sy = sy or self.sy
    if (self.spriteClone ~= nil) then
      self.spriteClone:draw(x, y, r, sx, sy, ox, oy, kx, ky)
    else
      local sprite = self.assets:getWithType(self.name, "sprite")
      sprite:drawAnimation(x, y, r, sx, sy, ox, oy, kx, ky)
    end
  end
end

return Sprite
