-------------------------------------------------------------------------------
-- Copyright (c) 2012 - Roland Yonaba
-- Entity
-------------------------------------------------------------------------------

local Class = require 'src.lib.30log'
local Entity = Class({ 
  gap_up = 0, gap_down = 0, 
  x = 0, y = 0, 
  grid_x = 0, grid_y = 0,
  width = 0, height = 0, 
  scale_x = 1, scale_y = 1, angle = 0,
})

-- Sets position on grid
function Entity:setGridPosition(x,y)
  self.x, self.y = x or self.x, y or self.y
end

-- Gets position on grid
function Entity:getGridPosition()
  return self.x, self.y
end

-- Gets the standing tile
function Entity:getTile(tile_map, x, y)
  x = x or self.grid_x
  y = y or self.grid_y 
  for _,tile in ipairs(tile_map) do
    if tile.x == x and tile.y == y then
      return tile
    end
  end
  return nil
end

-- Sets size
function Entity:setDimensions(width, height)
  self.width = width or self.width
  self.height = height or self.height
end

-- Sets image
function Entity:setImg(img)
  self.img = img
end

-- Sets display offsets for proper drawing
function Entity:setGap(up, down)
  self.gap_up, self.gap_down = up or 0, down or 0
end

-- Converts tiles coordinates to drawing coordinates
function Entity:getGridToWorldPosition()
  local to_world_x = (self.x-1)*self.width
  local to_world_y = (self.y - 1)*(self.height-(self.y > 1 and self.gap_up+self.gap_down or 0))
  return to_world_x, to_world_y
end

-- Draws entity
function Entity:draw(relative_x, relative_y)
  local draw_x, draw_y = self:getGridToWorldPosition()
  if relative_x then draw_x = draw_x + relative_x end
  if relative_y then draw_y = draw_y + relative_y end
  love.graphics.draw(self.img,draw_x,draw_y,self.angle, self.scale_x, self.scale_y)
end

return Entity