local Entity = require "scenes.levels.entities.parent"

local Weapon = Entity:extend()

function Weapon:new(level, x, y, id, xsp, ysp)
  Weapon.super.new(self, level, "weapon", x-8, y - 8, 16, 16)
  self.weaponid = id or 0
  self.xsp = xsp or 0
  self.ysp = ysp or 0
  self.rotation = 0
end

function Weapon:setFilter()
  self.filter = function(item, other)
    if     (other.collType=="wall")   then
      return 'touch'
    elseif (other.collType=="block")   then
      return "touch"
    elseif (other.collType=="ennemy")   then
      return "touch"
    else
      return nil
    end
  end
end

function Weapon:update(dt)
  self:setFilter()

  self.rotation = self.rotation + (dt * 90)*8

  local cols, cols_len = self:move(dt)

  for j=1,cols_len do
    local other = cols[j].other
    if other.collType=="wall" and (self.life == 1) then
      self:destroy()
    end
    if other.collType=="block" and (self.life == 1) then
      self:destroy()
      other:breakBlock()
    end
    if other.collType=="ennemy" and (self.life == 1) then
      self:destroy()
      other:getDamage(1)
    end
  end

  self.life = 1

  local isInsideView = self:isInsideView()
  if (isInsideView == false) then
    self:destroy()
  end

  self:getDirection()
end

function Weapon:draw(dt)
  local rotation = math.floor(self.rotation/45)*45
  drawx, drawy = self:getCenter()
  self.level.assets.tileset["weapon"]:drawTile(self.weaponid, drawx, drawy,
                                                rotation, self.direction, 1, 8, 8)
end

return Weapon
