from xml.dom.minidom import Document
import pyut_framework as pyut

class TestXmlReport(object):
    def save(self, filename, root_test_item, tests_configuration):
        """Creates XML report from the tests that are contained in the tree under passed root TestItem."""
        doc = Document()
        elem = self._create_test_item_elem(doc, root_test_item, tests_configuration)
        if elem:
            doc.appendChild(elem)
            xml_data = doc.toprettyxml()
            with open(filename, 'w') as report_file:
                report_file.write(xml_data)
        
    def _create_test_item_elem(self, doc, test_item, tests_configuration):
        """Recursive function that walks the test tree and creates testcase
        or testsuite XML element based on the item in the test tree.
        """
        elem = None
        if test_item.type == pyut.TestItemType.FUNCTION:
            if not test_item.status:
                return None
            elem = doc.createElement('testcase')
            elem.setAttribute('name', test_item.name)
            elem.setAttribute('time', '%.3f' % test_item.time)
            
            elem_fail_name = None
            if test_item.status.status == pyut.TestStatus.SKIP:
                elem_fail_name = 'skipped'
            elif test_item.status.status == pyut.TestStatus.FAIL:
                elem_fail_name = 'failure'
            elif test_item.status.status == pyut.TestStatus.ERROR:
                elem_fail_name = 'error'
            if elem_fail_name:
                elem_fail = doc.createElement(elem_fail_name)
                cdata = doc.createCDATASection(test_item.outcome)
                elem_fail.appendChild(cdata)
                elem.appendChild(elem_fail)
            if test_item.output:
                txt_out = doc.createTextNode(test_item.output)
                elem.appendChild(txt_out)
        else:
            # non-optimal, could aggregate in this recursion
            _, np, ns, nf, ne = pyut.aggregate_results(test_item)
            na = np + ns + nf + ne
            elem = doc.createElement('testsuite')
            elem.setAttribute('name', test_item.name)
            elem.setAttribute('time', '%.3f' % test_item.time)
            elem.setAttribute('tests', str(na))
            elem.setAttribute('failures', str(nf))
            elem.setAttribute('errors', str(ne))
            elem.setAttribute('skip', str(ns))
            
            for ti in test_item.get_children():
                child_elem = self._create_test_item_elem(doc, ti, tests_configuration)
                if child_elem:
                    elem.appendChild(child_elem)
            if not elem.hasChildNodes():
                return None
            
            if tests_configuration:
                test_item_id = pyut.get_test_item_id(test_item)
                section = ""
                if test_item.type == pyut.TestItemType.MODULE:
                    section = test_item_id.module_name
                elif test_item.type == pyut.TestItemType.CLASS:
                    section = test_item_id.module_name + "." + test_item_id.class_name
                else:
                    section = pyut.CONF_SECTION_ALL
                elem_confs = self._create_properties_elem(doc, tests_configuration, section)
                if elem_confs:
                    elem.appendChild(elem_confs)
        return elem
    
    def _create_properties_elem(self, doc, tests_configuration, section):
        """Creates properties element if there are some properties to write and returns it.
        Else returns None.
        """
        if tests_configuration.has_section(section):
            elem_confs = doc.createElement('properties')
            for k, v in tests_configuration.items(section):
                elem_conf = doc.createElement('property')
                elem_conf.setAttribute('name', k)
                elem_conf.setAttribute('value', v)
                elem_confs.appendChild(elem_conf)
            if elem_confs.hasChildNodes():
                return elem_confs
        return None
                