from xml.etree import ElementTree
from parallels.core.utils.common import read_file_contents

from parallels.plesk import messages
from parallels.core import MigrationError
from parallels.plesk.hosting_description.input_formats.base import InputFormat


class InputFormatXML(InputFormat):
    @property
    def name(self):
        return 'xml'

    def read(self, filename):
        file_contents = read_file_contents(filename)
        root = ElementTree.fromstring(file_contents)

        def parse(node):
            list_nodes = {
                'clients': 'client',
                'subscriptions': 'subscription',
                'addon_domains': 'addon_domain',
                'subdomains': 'subdomain',
                'databases': 'database',
                'mailboxes': 'mailbox'
            }

            if node.tag in list_nodes:
                result = []

                for child in node:
                    if child.tag != list_nodes[node.tag]:
                        raise MigrationError(messages.INVALID_TAG % (child.tag, list_nodes[node.tag]))
                    result.append(parse(child))

                return result
            else:
                if len(node) > 0:
                    result = {}
                    for child in node:
                        result[child.tag] = parse(child)
                    return result
                else:
                    return node.text

        return parse(root)
