# -*- coding: utf-8 -*-
from urllib.parse import urlparse

from intelmq.lib.bot import ParserBot


class MalwareDomainListParserBot(ParserBot):
    def add_http(self, url):
        """
        We can assume here, that everything is http by default if not given.
        """
        if '://' not in url:
            return 'http://' + url

    parse = ParserBot.parse_csv
    recover_line = ParserBot.recover_line_csv

    def parse_line(self, row, report):
        event = self.new_event(report)

        event.add("time.source", row[0].replace('_', ' ') + " UTC")
        if row[1] != '-':
            event.add("source.url", self.add_http(row[1]))
        if not event.add("source.ip", row[2], raise_failure=False):
            event.add("source.url", self.add_http(row[2]))
            event.add('source.ip', urlparse(row[2]).netloc)
        event.add("source.reverse_dns", row[3])
        event.add("event_description.text", row[4])

        abuse_contacts = []
        source_abuse = row[5].split(' ')
        for abuse in source_abuse:
            if abuse != '-' and '@' in abuse:
                abuse_contacts.append(abuse)
        if abuse_contacts:
            event.add("source.abuse_contact", ','.join(abuse_contacts))

        event.add("source.asn", int(row[6]))

        event.add('classification.type', 'malware')
        event.add("raw", self.recover_line(row))
        yield event


BOT = MalwareDomainListParserBot
