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

local object = require('aconf.object')
local super = object.super

local pth = require('aconf.path')


local DeferringCommitter = object.class(
   require('aconf.transaction.base').Transaction
)

function DeferringCommitter:init(backend)
   super(self, DeferringCommitter):init(backend)
   self.defer_paths = {}
   self.committed = true
end

function DeferringCommitter:defer(path) self.defer_paths[path] = true end

function DeferringCommitter:_set_multiple(mods)
   super(self, DeferringCommitter):_set_multiple(mods)

   if not self.committed then return end
   self.committed = false

   for _, mod in ipairs(mods) do
      local path, value = table.unpack(mod)
      while path > '/' do
	 if self.defer_paths[path] then return end
	 path = pth.parent(path)
      end
   end

   self:commit()
end

function DeferringCommitter:commit()
   super(self, DeferringCommitter):commit()
   self.committed = true
end


return DeferringCommitter(require('aconf.persistence'))
