# Copyright (c) 2014, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# Generated Thu Apr 11 15:07:47 2013 by generateDS.py version 2.9a.
#

import sys
from stix.bindings import *
import stix.bindings.ttp as ttp_binding
try:
    from maec.bindings.maec_package import PackageType
    maec_installed = True
except ImportError:
    maec_installed = False

XML_NS = "http://stix.mitre.org/extensions/Malware#MAEC4.1-1"

#
# Data representation classes.
#

class MAEC4_1InstanceType(ttp_binding.MalwareInstanceType):
    """The MAEC4.1InstanceType provides an extension to ttp_binding.MalwareInstanceType
    which imports and leverages the MAEC 4.0.1 schema for structured
    characterization of Malware."""
    subclass = None
    superclass = ttp_binding.MalwareInstanceType
    def __init__(self, Type=None, Name=None, Description=None, MAEC=None):
        super(MAEC4_1InstanceType, self).__init__(Type=Type, Name=Name, Description=Description)
        self.xmlns          = XML_NS
        self.xmlns_prefix   = "stix-maec"
        self.xml_type       = "MAEC4.1InstanceType"
        self.MAEC = MAEC
    def factory(*args_, **kwargs_):
        if MAEC4_1InstanceType.subclass:
            return MAEC4_1InstanceType.subclass(*args_, **kwargs_)
        else:
            return MAEC4_1InstanceType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_MAEC(self): return self.MAEC
    def set_MAEC(self, MAEC): self.MAEC = MAEC
    def hasContent_(self):
        if (
            self.MAEC is not None or
            super(MAEC4_1InstanceType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='MAEC4.1InstanceType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='MAEC4.1InstanceType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_='', name_='MAEC4.1InstanceType'):
        super(MAEC4_1InstanceType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='MAEC4.1InstanceType')
        if 'xsi:type' not in already_processed:
            already_processed.add('xsi:type')
            xsi_type = " xsi:type='%s:%s'" % (self.xmlns_prefix, self.xml_type)
            lwrite(xsi_type)
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='MAEC4.1InstanceType', fromsubclass_=False, pretty_print=True):
        super(MAEC4_1InstanceType, self).exportChildren(lwrite, level, nsmap, ttp_binding.XML_NS, name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.MAEC is not None:
            if maec_installed and isinstance(self.MAEC, PackageType):
                self.MAEC.export(lwrite, level, namespace_='stix-maec:', name_='MAEC', pretty_print=pretty_print)
            else:
                showIndent(lwrite, level, pretty_print)
                lwrite(etree_.tostring(self.MAEC, pretty_print=pretty_print))
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        super(MAEC4_1InstanceType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'MAEC':
            if maec_installed:
                obj_ = PackageType.factory()
                obj_.build(child_)
                self.set_MAEC(obj_)
            else:
                self.set_MAEC(child_)
        super(MAEC4_1InstanceType, self).buildChildren(child_, node, nodeName_, True)
# end class MAEC4_1InstanceType

GDSClassesMapping = {}

USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""

def usage():
    print USAGE_TEXT
    sys.exit(1)

def get_root_tag(node):
    tag = Tag_pattern_.match(node.tag).groups()[-1]
    rootClass = GDSClassesMapping.get(tag)
    if rootClass is None:
        rootClass = globals().get(tag)
    return tag, rootClass

def parse(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'MAEC4.1InstanceType'
        rootClass = MAEC4_1InstanceType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    #sys.stdout.write('<?xml version="1.0" ?>\n')
    #rootObj.export(sys.stdout, 0, name_=rootTag,
    #    namespacedef_='',
    #    pretty_print=True)
    return rootObj

def parseEtree(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'MAEC4.1InstanceType'
        rootClass = MAEC4_1InstanceType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    rootElement = rootObj.to_etree(None, name_=rootTag)
    content = etree_.tostring(rootElement, pretty_print=True,
        xml_declaration=True, encoding="utf-8")
    sys.stdout.write(content)
    sys.stdout.write('\n')
    return rootObj, rootElement

def parseString(inString):
    from StringIO import StringIO
    doc = parsexml_(StringIO(inString))
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'MAEC4.1InstanceType'
        rootClass = MAEC4_1InstanceType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    #sys.stdout.write('<?xml version="1.0" ?>\n')
    #rootObj.export(lwrite=sys.stdout, level=0, name_="MAEC4.1InstanceType",
    #    namespacedef_='')
    return rootObj

def main():
    args = sys.argv[1:]
    if len(args) == 1:
        parse(args[0])
    else:
        usage()

if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()

__all__ = [
    "MAEC4_1InstanceType"
    ]