# -*- coding: utf-8 -*-
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])
            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('classification.type', 'malware')
            event.add('raw', row)

            self.send_message(event)
        self.acknowledge_message()


BOT = MalwareDomainsParserBot
