from __future__ import absolute_import
from xml.etree import ElementTree
from copy import deepcopy
from xml.dom import minidom
from cStringIO import StringIO


def seq(*items):
	return [item for item in items if item is not None]


def seq_iter(items):
	return seq(*items)


def elem(name, children=None, attrs=None):
	if children is None:
		children = []
	if attrs is None:
		attrs = {}
	n = ElementTree.Element(name, attrs)
	n.extend(children)
	return n


def text_elem(name, value, attrs=None):
	if value is None:
		return None
	if attrs is None:
		attrs = {}
	el = ElementTree.Element(name, attrs)
	el.text = unicode(value)
	return el


def xml_bool(value):
	return 'true' if value else 'false'


def bool_elem(name, value):
	return text_elem(name, xml_bool(value))


def create_xml_stream(xml, xml_declaration=True):
	stream = StringIO()
	xml.write(stream, xml_declaration=xml_declaration, encoding='utf-8')
	stream.seek(0)
	return stream


def replace_root_node_if_name_matches(source_xml, root_tag_name, new_root_node):
	if source_xml.tag == root_tag_name:
		target_xml = deepcopy(new_root_node)
		for child in source_xml:
			target_xml.append(deepcopy(child))
		return target_xml
	else:
		return deepcopy(source_xml)


def multiple_findall(node, paths):
	for path in paths:
		for found in node.findall(path):
			yield found


def multiple_find(node, paths):
	for path in paths:
		found = node.find(path)
		if found is not None:
			return found
	return None


def multiple_attrib_get(node, attrib_names, default=None):
	for attrib_name in attrib_names:
		if attrib_name in node.attrib:
			return node.attrib[attrib_name]
	return default


def prettify_xml(xml_string):
	"""Prettify XML with indentation

	:type xml_string: basestring
	:rtype: basestring
	"""
	xml = minidom.parseString(xml_string)
	return xml.toprettyxml(indent='  ', encoding='utf-8')


def xml_to_string_pretty(tree):
	"""Serialize XML into a string, with pretty indentation

	:type tree: xml.etree.ElementTree.ElementTree
	:rtype: basestring
	"""
	return prettify_xml(
		ElementTree.tostring(tree.getroot(), 'utf-8', 'xml')
	)
