from __future__ import absolute_import
from xml.etree import ElementTree
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=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):
	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
