--[[
Copyright (c) 2012-2013 Kaarle Ritvanen
See LICENSE file for license details
--]]

local M = {}

local TreeNode = require('acf2.model.field').TreeNode
local npairs = require('acf2.model.node').pairs
local object = require('acf2.object')


M.Set = object.class(require('acf2.model.node').List)

function M.Set:init(context, params)
   assert(not object.isinstance(params.field, TreeNode))
   object.super(self, M.Set):init(context, params)

   local function find(value)
      for i, member in npairs(self) do
	 if member == value then return i end
      end
   end

   local mt = getmetatable(self)
   mt.dereference = false
   mt.meta.type = 'set'

   function mt.get(k, create)
      local i = find(k)
      if i then return mt.load(i) end
      if create then return k end
   end

   function mt.__newindex(t, k, v)
      assert(v == nil)
      local i = find(k)
      if not i then return end
      mt.save(i, nil)
   end

   local insert = mt.insert
   function mt.insert(v) if not find(v) then insert(v) end end
end


return M
