from datetime import datetime, timedelta
import logging

from core.observables import Hostname
from core.feed import Feed
from core.errors import ObservableValidationError


class MalwareDomainsDotCom(Feed):

    default_values = {
        "frequency": timedelta(hours=2),
        "name": "MalwareDomainsDotCom",
        "source": "http://mirror1.malwaredomains.com/files/domains.txt",
        "description": "Malwaredomains.com Blacklist",
    }

    def update(self):

        for line in self.update_lines():
            self.analyze(line)

    def analyze(self, line):

        line = line.strip()
        sline = line.split()

        try:
            if line[0] != '#' and len(
                    sline
            ) > 3:  # ignore comments and entries with no clear reference

                if sline[0].isdigit():
                    sline.pop(0)

                hostname = sline[0]
                description = sline[1]
                reference = sline[2]
                if sline[3] == 'relisted':
                    date = sline[4]
                else:
                    date = sline[3]

                context = {}
                context['source'] = self.name
                context['description'] = description  # malware, EK, etc
                context[
                    'reference'] = reference  # GG safe browsing, blog, other blacklist, etc...
                context['date_added'] = datetime.strptime(date, "%Y%m%d")

                try:
                    hn = Hostname.get_or_create(value=hostname)
                    hn.add_context(context)
                    hn.add_source("feed")
                    hn.tag([description])
                except ObservableValidationError as e:
                    logging.error(e)
        except Exception:
            pass
