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

--- @module aconf.model
local M = {}

local TreeNode = require('aconf.model.field').TreeNode
local node = require('aconf.model.node')
local object = require('aconf.object')
local pth = require('aconf.path')
local util = require('aconf.util')


--- set object, inherits @{node.List}. An instance of this class represents
-- a set object in the data model, in the context of a specific
-- transaction. A set is an unordered collection of primitive
-- values. Members can be inserted to the set using
-- @{node.insert}. Members can be removed by assigning the nil value
-- to the key to be removed.
-- @klass node.Set
M.Set = object.class(require('aconf.model.node').List)

function M.Set:init(context, params)
   assert(not object.isinstance(params.field, TreeNode))
   params.field.dereference = false

   params.dtype = 'set'

   object.super(self, M.Set):init(context, params)

   local function find(value)
      value = node.BoundMember(
	 self, pth.wildcard, params.field
      ):normalize(value)

      for i, member in pairs(self) do
	 if member == value then return i, value end
      end
   end

   local mt = getmetatable(self)

   function mt.get(k, options)
      options = util.setdefaults(options, {dereference=true})
      local i, v = find(k)
      if i then return mt.load(i, options) end
      if options.create then return v 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

   --- determines if the given set contains the given value.
   -- @function node.contains
   -- @tparam node.Set set set
   -- @tparam primitive v value
   -- @treturn boolean true if the set contains the value
   function mt.contains(v) return find(v) and true or false end

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

   local meta = mt.meta
   function mt.meta()
      local res = meta()
      res.removable = util.map(mt.load, res.removable)
      return res
   end
end


return M
