local insert = table.insert

local Concord = require("lib.Concord")

-- Modules
local Entity     = Concord.entity
local Component  = Concord.component
local System     = Concord.system
local World      = Concord.world

-- Containers
local Components  = Concord.components


local constructor = {}

constructor.systems = {}

local function is_component_complete(pool)
  local is_complete = true
  for _, v in pairs(pool) do
    for _, c in ipairs(v) do
      if (Components.has(c) == false) then
        is_complete = false
        break
      end
    end
    if (not is_complete) then
      break
    end
  end
  return is_complete
end

function constructor.new(name, pool)
  if (constructor.systems[name]) then
    return constructor.systems[name]
  else
    if (type(pool) == "table") then
      if (is_component_complete(pool)) then
        local self = System(pool)
        self.name = name
        constructor.systems[name] = self
        return self
      else
        return nil
      end
    else
      error("new system register error. pool and wrapper should be a table.")
      return nil
    end
  end
end

function constructor.add(world, path)
  local namespace = {}
  if (type(path) == "string") then
    Concord.utils.loadNamespace(path, namespace)
  else
    for k,v in pairs(path) do
      if type(v) == "string" then
        local new_namespace = {}
        Concord.utils.loadNamespace(v, new_namespace)
        for l, w in pairs(new_namespace) do
          namespace[l] = w
        end
      else
        insert(namespace, v)
      end
    end
  end
  for k,v in pairs(namespace) do
    local new_sys = v.new()
    if (new_sys == nil) then

    else
      if not world:hasSystem(new_sys) then
        world:addSystems(new_sys)
      end
    end
  end
end

return constructor
