# -*- coding: utf-8 -*-
"""
The descriptions give a hint about what the entry is about and is very mixed.
Most prominent description is "phishing", most of them are malware names.
More types could be mapped better, only the most obvious ones are done currently.
"""
import datetime

from intelmq.lib import utils
from intelmq.lib.bot import Bot


class MalwareDomainsParserBot(Bot):

    def is_valid_date(self, strd):
        try:
            datetime.datetime.strptime(strd, '%Y%m%d')
            return True
        except Exception:
            return False

    def process(self):
        report = self.receive_message()

        raw_report = utils.base64_decode(report.get("raw"))

        for row in raw_report.splitlines():
            row = row.rstrip()

            if row.startswith("#") or len(row) == 0:
                continue

            values = row.split('\t')[1:]

            event = self.new_event(report)

            event.add('source.fqdn', values[1])
            if values[2] == 'phishing':
                event.add('classification.identifier', values[2])
                event.add('classification.type', 'phishing')
            elif values[2] == 'C&C':
                event.add('classification.identifier', values[2])
                event.add('classification.type', 'c2server')
            else:
                event.add('classification.identifier', values[2])
                event.add('classification.type', 'malware')
            event.add('event_description.text', values[2])

            for i in range(4, len(values)):
                if self.is_valid_date(values[i]):
                    event.add('time.source',  # times are GMT, verified via email
                              values[i] + "T00:00:00+00:00", overwrite=True)
                    break

            event.add('raw', row)

            self.send_message(event)
        self.acknowledge_message()


BOT = MalwareDomainsParserBot
