# -*- coding: utf-8 -*-

import cache
from buddies import Contacts

class FoundNodes:
	"""list of found nodes"""
	foundNodes = {}

class Search:
	"""performs search operations"""
	__implemented = ('murray_id', 'alias')		#implemented searchfields
	__cache = cache.KnownPeers()
	__buddyList = Contacts()
	
	def search(self, searchfields, operation):
		"""performs a search according to the searchfields-dictionary.
		
		returns the dictionary of found results"""
		found = FoundNodes()
		if operation == 'or':
			for key in searchfields.keys():
				if key in self.__implemented:
					function = getattr(self, key)
					function(searchfields[key], found)
				else:
					pass
		else:
			for key in searchfields.keys():
				if key in self.__implemented:
					function = getattr(self, key)
					newfound = function(searchfields[key], found)
					for items in found.foundNodes.keys():
						if item not in newfound:
							del found[item]
				else:
					pass
		return found.foundNodes
				
		
	def murray_id(uid, foundList):
		"""searches for a murray_id and adds the nodes to foundNodes.
		
		returns a list of found nodes"""
		if cache.known(uid):
			data = cache.getByMurray_ID(uid)
			foundList.foundNodes[uid] = data
			return [uid]
		else:
			return []

	def alias(alias, foundList):
		"""searches for user alias
		returns a list of found nodes"""
		
		if alias == globalv.ALIAS:
			foundList.foundNodes[globalv.MURRAY_ID] = {'ipversion':globalv.IP_VERSION, 'ip':globalv.IP,
			'port':globalv.PORT}
			return [globalv.MURRAY_ID]
		elif __buddyList.getMurrayID(alias):
			ham = __buddy.getMurrayID(alias)
			foundList.foundNodes[ham] = __cache.getByMurray_ID(ham)
			return [ham]