from __future__ import absolute_import
from xml.etree import ElementTree as et
from copy import deepcopy

from cStringIO import StringIO

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

def elem(name, children=[], attrs={}):
	n = et.Element(name, attrs)
	n.extend(children)
	return n

def text_elem(name, value, attrs={}):
	if value is None:
		return None
	el = et.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):
	stream = StringIO()
	xml.write(stream, xml_declaration=True, 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
