local system_constructor = require("love_src.wrapper.Concord.system")
local c_button = require("love_src.src.world.common.component.button")

local system = {}

system.__index = system

system.pool = {
  pool = {
    c_button.dict.collider,
    c_button.dict.func,
    c_button.dict.label
  }
}

system.components = {
  [c_button.dict.collider] = c_button.collider,
  [c_button.dict.func] = c_button.func,
  [c_button.dict.label] = c_button.label
}

function system.new()
  local new_system = system_constructor.new("trigger_button", system.pool)
  if (new_system) then
    for k, v in pairs(system) do
		  new_system[k] = v
	  end
    return new_system
  else
    return nil
  end
end

-- x1 y1        -- (x1 + w1) y1
--          x2 y2
-- x1 (y1 + h1) -- (x1 + w1) (y1 + h1)
local function is_inside(x1,y1,w1,h1, x2,y2)
  return x1 < x2 and
         x2 < x1+w1 and
         y1 < y2 and
         y2 < y1+h1
end

function system:mousereleased(x, y, button, istouch, presses)
  for _, e in ipairs(self.pool) do
    local x1 = e[c_button.dict.collider].data.x
    local y1 = e[c_button.dict.collider].data.y
    local w1 = e[c_button.dict.collider].data.w
    local h1 = e[c_button.dict.collider].data.h
    local func = e[c_button.dict.func].data
    if (is_inside(x1, y1, w1, h1, x, y) and button == 1) then
      func()
    end
  end
end

local function draw(text, x, y, w, h)
  love.graphics.push()
  love.graphics.line(
    x, y,
    x + w, y,
    x + w, y + h,
    x, y + h,
    x, y
  )
  love.graphics.print(text, x, y)
  love.graphics.pop()
end

function system:draw()
  for _, e in ipairs(self.pool) do
    local x = e[c_button.dict.collider].data.x
    local y = e[c_button.dict.collider].data.y
    local w = e[c_button.dict.collider].data.w
    local h = e[c_button.dict.collider].data.h
    local label = e[c_button.dict.label].data
    draw(label, x, y, w, h)
  end
end

return system
