import logging
from datetime import datetime, timedelta

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


class MalwareMustDieCncs(Feed):
    default_values = {
        "frequency": timedelta(hours=24),
        "name": "MalwareMustDieCncs",
        "source": "https://malwared.malwaremustdie.org/rss.php",
        "description": "List of cncs",
    }

    def update(self):
        since_last_run = datetime.now() - self.frequency

        for item in self.update_xml("item", ["title", "description"]):
            if self.last_run is not None:
                try:
                    if (
                        datetime.strptime(item["description"], "%d/%b/%Y")
                        < since_last_run
                    ):
                        continue
                except ValueError:
                    if (
                        datetime.strptime(item["description"], "%d/%B/%Y")
                        < since_last_run
                    ):
                        continue
            self.analyze(item["title"])

    def analyze(self, cnc):
        try:
            cnc_data = Hostname.get_or_create(value=cnc)
            cnc_data.add_context(
                {"source": self.name, "date_added": datetime.utcnow()},
                dedup_list=["date_added"],
            )
            cnc_data.add_source(self.name)
        except ObservableValidationError as e:
            logging.error(e)
