xmlDb = {}
xmlDb_mt = { __index = xmlDb }

local path = ":"..getResourceName(getThisResource()).."/db/"

function getRealType(typ,val)
	if (typ=="number") then
		return tonumber(val)
	elseif (typ=="string") then
		return tostring(val)
	end
end

function xmlDb:create(name) 
	local new = {}
	setmetatable(new, xmlDb_mt)
	new:open(name)
	return new
end

function xmlDb:open(name)
	self.path = path..name..".xml"
	if fileExists(self.path) then
		self.db = xmlLoadFile(self.path)
	else 
		self.db = xmlCreateFile(self.path,"root")
		xmlSaveFile(self.db)
	end
	if not self.db then 
		outputDebugString("Something bad happened while loading/creating database!")
		return false
	end
	return self
end

function xmlDb:close()
	if not self.db then 
		outputDebugString("Something bad happened while saving/closing database!")
	else 
		xmlSaveFile(self.db)
		xmlUnloadFile(self.db)
		self = nil
	end
end

function xmlDb:hasKey(key)
	for i,v in ipairs(xmlNodeGetChildren(self.db)) do
		if (getRealType(xmlNodeGetAttribute(v,"keytype"),xmlNodeGetAttribute(v,"key")) == key) then 
			return true
		end
	end
	return false
end

function xmlDb:insert(key,value)
	if self:hasKey(key) then return "Duplicate key found!" end
	local child = xmlCreateChild(self.db, "row")
	xmlNodeSetAttribute(child,"key",key)
	xmlNodeSetAttribute(child,"value",toJSON(value))
	xmlNodeSetAttribute(child,"keytype",type(key))
	xmlNodeSetAttribute(child,"lastupdate",getTickCount())
	xmlSaveFile(self.db)
	return self
end

function xmlDb:update(key,value)
	if self:hasKey(key) then
		for i,v in ipairs(xmlNodeGetChildren(self.db)) do
			if (getRealType(xmlNodeGetAttribute(v,"keytype"),xmlNodeGetAttribute(v,"key")) == key) then 
				xmlNodeSetAttribute(v,"key",key)
				xmlNodeSetAttribute(v,"value",toJSON(value))		
				xmlNodeSetAttribute(v,"keytype",type(key))
				xmlNodeSetAttribute(v,"lastupdate",getTickCount())
				break
			end
		end
		xmlSaveFile(self.db)
		return true
	else 
		return false, "No key found!" 			
	end
end

function xmlDb:delete(key)
	if self:hasKey(key) then
		for i,v in ipairs(xmlNodeGetChildren(self.db)) do
			if (getRealType(xmlNodeGetAttribute(v,"keytype"),xmlNodeGetAttribute(v,"key")) == key) then 
				xmlDestroyNode(v)
				break
			end
		end
		xmlSaveFile(self.db)
		return self, true
	else 
		return self, false, "No key found!" 			
	end
end

function xmlDb:getall()
	local data = {}
	for i,v in ipairs(xmlNodeGetChildren(self.db)) do
		table.insert(data,{ key=xmlNodeGetAttribute(v,"key"), data=fromJSON(xmlNodeGetAttribute(v,"value")) })
	end
	return data
end

function xmlDb:get(key)
	if self:hasKey(key) then
		for i,v in ipairs(xmlNodeGetChildren(self.db)) do
			local nkey = getRealType(xmlNodeGetAttribute(v,"keytype"),xmlNodeGetAttribute(v,"key"))
			if ( nkey == key) then 
				return { key=nkey, data=fromJSON(xmlNodeGetAttribute(v,"value")) }
			end
		end
	else 
		return false, "No key found!" 			
	end
end

