from xml_utils import get_attribute, get_content_of, get_element, as_string
from itertools import imap


class VulnerabilityReference:
    @staticmethod
    def CreateFromXML(xml_data):
        reference = VulnerabilityReference()
        reference.source = get_attribute(xml_data, 'source', reference.source)
        return reference

    def __init__(self):
        self.source = ''


class VulnerabilityBase:
    def InitalizeFromXML(self, xml_data):
        self.id = get_attribute(xml_data, 'id', self.id)
        self.title = get_attribute(xml_data, 'title', self.title)
        self.severity = int(get_attribute(xml_data, 'severity', self.severity))
        self.pci_severity = int(get_attribute(xml_data, 'pciSeverity', self.pci_severity))
        self.cvss_score = float(get_attribute(xml_data, 'cvssScore', self.cvss_score))
        self.cvss_vector = get_attribute(xml_data, 'cvssVector', self.cvss_vector)
        self.requires_credentials = get_attribute(xml_data, 'requiresCredentials', self.requires_credentials) in ['1', 'true']
        self.is_safe = get_attribute(xml_data, 'safe', self.is_safe) in ['1', 'true']
        self.published = get_attribute(xml_data, 'published', self.published)
        self.added = get_attribute(xml_data, 'added', self.added)
        self.modified = get_attribute(xml_data, 'modified', self.modified)

    def __init__(self):
        self.id = ''
        self.title = ''
        self.severity = 0
        self.pci_severity = 0
        self.cvss_score = 0
        self.cvss_vector = ''
        self.requires_credentials = False
        self.is_safe = False
        self.published = ''
        self.added = ''
        self.modified = ''


class VulnerabilitySummary(VulnerabilityBase):
    @staticmethod
    def CreateFromXML(xml_data):
        summary = VulnerabilitySummary()
        summary.InitalizeFromXML(xml_data)
        return summary

    def __init__(self):
        VulnerabilityBase.__init__(self)


class VulnerabilityDetail(VulnerabilityBase):
    @staticmethod
    def CreateFromXML(xml_data):
        xml_description = get_element(xml_data, 'description')
        xml_solution = get_element(xml_data, 'solution')

        reference_generator = imap(lambda xml_reference: VulnerabilityReference.CreateFromXML(xml_reference), xml_data.iterfind('references/reference'))
        config = VulnerabilityDetail()
        config.InitalizeFromXML(xml_data)
        config.description = as_string(xml_description) if xml_description is not None else config.description
        config.references = list(reference_generator)
        config.solution = as_string(xml_solution) if xml_solution is not None else config.solution
        return config

    def __init__(self):
        VulnerabilityBase.__init__(self)
        self.description = ''
        self.references = []
        self.solution = ''
