
from __future__ import absolute_import
from __future__ import division

import copy
import io
import xml.etree.ElementTree as etree

import six


def fromstring(data):
    parser = etree.XMLParser()
    if isinstance(data, six.binary_type):
        parser.feed(data)
    else:
        parser.feed(data.encode('utf-8'))
    return parser.close()


def tostring(element, pretty=False):
    if pretty:
        element = copy.deepcopy(element)
        indent(element, 0)
    stream = io.BytesIO()
    etree.ElementTree(element).write(
        stream, encoding='utf-8', xml_declaration=True)
    return stream.getvalue().decode('utf-8')


def indent(element, level=0, s="    "):
    i = "\n" + level * s
    if len(element):
        if not element.text or not element.text.strip():
            element.text = i + s
        if not element.tail or not element.tail.strip():
            element.tail = i
        for element in element:
            indent(element, level + 1, s)
        if not element.tail or not element.tail.strip():
            element.tail = i
    else:
        if level and (not element.tail or not element.tail.strip()):
            element.tail = i
