--
-- Lua - libstatgrab extender.
--

local assert,error,pairs,ipairs = assert,error,pairs,ipairs
local setmetatable,tostring = setmetatable,tostring
local yield,wrap = coroutine.yield,coroutine.wrap

require "libstatgrab"

module "sg"

function startup()
	if	init() ~= 0 or drop_privileges() ~= 0
	then	error(str_error(get_error()))
	end
end

local t = {
	"host_info",
	"cpu_stats",
	"cpu_stats_diff",
	"cpu_percents",
	"mem_stats",
	"load_stats",
	"user_stats",
	"swap_stats",
	"page_stats",
	"page_stats_diff",
	"process_count"
}

for _,v in ipairs(t) do
	_M[v] = function ()
		local t = assert(_M["get_".. v](),str_error(get_error()))
		return t
	end
end

t = {
	fs_stats =	"device_name",
	disk_io_stats =	"disk_name",
	disk_io_stats_diff =	"disk_name",
	network_io_stats =	"interface_name",
	network_io_stats_diff =	"interface_name",
	network_iface_stats =	"interface_name",
	process_stats =	"process_name"
}

MT = {}

function MT.match( t,pat,field )
	field = field or t.DEFAULTFIELD
	for _,v in ipairs(t) do
		if	tostring(v[field]):match(pat)
		then	return v
		end
	end
end

function MT.gmatch( t,pat,field )
	field = field or t.DEFAULTFIELD
	return wrap(function ()
		for _,v in ipairs(t) do
			if	tostring(v[field]):match(pat)
			then	yield(v)
			end
		end
	end)
end

for k,v in pairs(t) do
	MT[k] = {__index = {DEFAULTFIELD = v,match = MT.match,gmatch = MT.gmatch}}
	_M[k] = function ()
		local t = assert(_M["get_".. k](),str_error(get_error()))
		return setmetatable(t,MT[k])
	end
end

return _M
