"""
DCSO TIE2MISP Parser
Copyright (c) 2017, DCSO GmbH
"""
from model.attributes import DomainName, URLVerbatim, MD5, SHA1, SHA256
from model.misp_event import MISPEvent
from model.misp_tag import MISPTag


class Malware(MISPEvent):

    def __init__(self, organisation_name, organisation_uuid, threat_level_id, published, info, date):
        MISPEvent.__init__(self, organisation_name, organisation_uuid, threat_level_id, published, info, date)
        self.append_tags(MISPTag("#ffc000", True, "tlp:amber"))

    @staticmethod
    def parse(misp_event, val):
        if isinstance(misp_event, Malware) and isinstance(val, list):
            index = 1
            length = len(val)
            for item in val:
                #print(item["data_type"])
                if item["data_type"] == 'ExactHash':
                    try:
                        value = ""
                        value = item["value"]
                        if value.startswith('md5'):
                            md5 = MD5.parse(item)
                            misp_event.append_attribute(md5)
                        elif value.startswith('sha1'):
                            sha1 = SHA1.parse(item)
                            misp_event.append_attribute(sha1)
                        elif value.startswith('sha256'):
                            sha256 = SHA256.parse(item)
                            misp_event.append_attribute(sha256)
                        else:
                            raise ValueError('Error parsing ExactHash - Value must be from type md5,sha1 or sha256')

                    except ValueError:
                        print("Error parsing TIE IOC(ExactHash)")
                elif item["data_type"] == "DomainName":
                    try:
                        dn = DomainName.parse(item)
                        misp_event.append_attribute(dn)
                    except ValueError:
                        print("Error parsing TIE IOC(DomainName)")
                elif item["data_type"] == "URLVerbatim":
                    try:
                        url = URLVerbatim.parse(item)
                        misp_event.append_attribute(url)
                    except ValueError:
                        print("Error parsing TIE IOC(URLVerbatim)")
                else:
                    raise ValueError("Malware events only supports attributes with type md5, sha1, sha256, "
                                     "DomainName, URLVerbatim\n Event is: " + item["data_type"])
                if index%10 == 0 or index == length:
                    print('Attribute: ' + str(index) + ' from ' + str(length))
                index += 1
        else:
            raise ValueError("Error parsing event - given event must be a C2Server event")



