from collections import defaultdict

from parallels.common.hosting_check import BaseHostingObject
from parallels.common.hosting_check import BaseHostingCheckSource
from parallels.common.hosting_check import ChildHostingObjectsList
from parallels.common.hosting_check import HostingCheckEntitiesList

"""Compound several hosting objects trees

If you have multiple sources of checks, you can put them into a single tree
of hosting objects with the help of this object
"""
class CompoundHostingObject(BaseHostingObject):
	def __init__(self, hosting_objects):
		self.hosting_objects = hosting_objects
		self.name = hosting_objects[0].name
		self.type = hosting_objects[0].type

	def get_hosting_check_entities(self):
		all_entities = HostingCheckEntitiesList()

		for hosting_object in self.hosting_objects:
			single_entities = hosting_object.get_hosting_check_entities()
			all_entities.issues.extend(single_entities.issues)
			all_entities.hosting_check_entities.extend(
				single_entities.hosting_check_entities
			)

		return all_entities

	def get_child_hosting_objects(self):
		result = ChildHostingObjectsList()
		all_child_objects = defaultdict(list)

		for hosting_object in self.hosting_objects:
			child_objects = hosting_object.get_child_hosting_objects()
			result.issues.extend(child_objects.issues)
			for child_object in child_objects.child_hosting_objects:
				key = (child_object.name, child_object.type)
				all_child_objects[key].append(child_object)
		for child_objects in all_child_objects.itervalues():
			result.child_hosting_objects.append(
				CompoundHostingObject(child_objects)
			)

		return result

"""Compound several check sources into single one

If you have multiple sources of checks, you can put them into a single tree
of hosting objects with the help of this object
"""
class CompoundHostingCheckSource(BaseHostingCheckSource):
	def __init__(self, sources):
		self.sources = sources
		
	def get_root_hosting_object(self):
		return CompoundHostingObject([
			source.get_root_hosting_object()
			for source in self.sources
		])

