try:
    from xml.etree import cElementTree as etree
except ImportError:
    from xml.etree import ElementTree as etree


class TagDescriptor(object):
    def __get__(_self, _instance, cls):
        return getattr(cls, '__tag__', None) or cls.__name__


class TypeNameDescriptor(object):
    def __get__(_self, instance, cls):
        return instance.attributes.get('name') if instance else cls.tag


def resolve_type(etype):
    if isinstance(etype, TypeAlias) or (type(etype) is type and issubclass(etype, TypeAlias)):
        return etype.get_real_type()
    else:
        return etype


class Node(object):
    tag = TagDescriptor()
    type_name = TypeNameDescriptor()

    def __init__(self, **attributes):
        self.attributes = attributes.copy()
        self.children = []

    def __call__(self, *children):
        self.children.extend(children)
        return self

    def get_node(self, creator):
        attributes = self.attributes
        if 'type' in attributes:
            attributes = attributes.copy()
            etype = resolve_type(attributes['type'])
            attributes['type'] = creator.get_prefixed_tag(etype.namespace, etype.type_name)

        if 'base' in attributes:
            attributes = attributes.copy()
            etype = resolve_type(attributes['base'])
            attributes['base'] = creator.get_prefixed_tag(etype.namespace, etype.type_name)

        node = creator(self.__class__.namespace, self.tag, attributes)