from xml.etree import ElementTree


class ErrorDocumentsXMLConverter(object):
    def __init__(self):
        self.path_convert_function = None

    def set_path_convert_function(self, path_convert_function):
        self.path_convert_function = path_convert_function

    def convert(self, subscription, site, xml_str):
        result = xml_str
        if self.path_convert_function is not None:
            result = self._convert_paths(subscription, site, result, self.path_convert_function)
        return result

    @staticmethod
    def _convert_paths(subscription, site, xml_str, path_convert_function):
        """

        Arguments:
        - path_convert_function - function with signature path_convert_function(subscription, site, vdir_path),
        where vdir_path is a path of a virtual directory in source virtual directory XML. The function should return
        corresponding path to the provided directory on the target server.
        """
        xml = ElementTree.XML(xml_str)
        for node in xml.findall('error'):
            if node.attrib['type'] == 'File':
                node.attrib['location'] = path_convert_function(
                    subscription, site,
                    node.attrib['location'],
                )
        return ElementTree.tostring(xml, 'utf-8', 'xml')