import requests  # Apache 2.0
import numpy as np
from bs4 import BeautifulSoup  # MIT
from datetime import date, datetime


class ModuleToday:
    def __init__(self, log):
        self.tag = "%20s - " % "mToday"
        self.log = log

        # self.load_today_from_csv(group)
        self.update()
        self.log.debug(f"{self.tag}Modul Today geladen")

    def loadTodayEvents(self):
        try:
            response = requests.get(
                f"https://history.muffinlabs.com/date", headers={"Accept": "application/json"})
            result = response.json()
            self.log.debug(f"{self.tag}Done loading events")
            
            return result['data']['Events']
        except (SyntaxError, ValueError) as exc:
            self.log.warning(
                f"{self.tag}Error while  loading events: {exc}")
            return []

    def getTodayMessage(self):
        message = ""

        today = date.today()
        sToday = today.strftime("%d.%m.%Y")
        message += f"Heute ist der {sToday}\n"
        # message += f"Der Tag dauert {self.sun['day_length']} Stunden.\n"
        # message += f"Sonnenaufgang: {self.sun['sunrise']}\n"
        # message += f"Sonnenuntergang: {self.sun['sunset']}\n"

        message += "\nWhat holiday is today?\n"
        for title in self.whatIsList:
            message += f'- {title}\n'

        facts = np.random.choice(self.todayEvents, 5)
        message += '\n5 Random History Facts about today:\n'
        for fact in facts:
            message += f'In {fact["year"]}: {fact["text"]}\n'

        return message

    def crawl_what_is_list(self):
        temp_list = []
        try:
            data = requests.get(
                "https://nationaltoday.com/what-is-today/").text
            soup = BeautifulSoup(data, features="html.parser")

            for title in soup.find_all(class_="holiday-title"):
                name = title.text
                if name not in temp_list:
                    temp_list.append(name)
        except Exception as ex:
            self.log.error(
                f"{self.tag}Failed crawling what-is-today list: {ex}")
        return temp_list

    def loadTodaySun(self):
        try:
            response = requests.get(
                f"https://api.sunrise-sunset.org/json?lat=51.2277411&lng=6.7734556&date=today", headers={"Accept": "application/json"})
            result = response.json()
            self.log.debug(f"{self.tag}Done loading sun informations")
            return result['results']

        except (SyntaxError, ValueError) as exc:
            self.log.warning(
                f"{self.tag}Error while sun informations events: {exc}")
            return []
            
    def update(self):
        self.todayEvents = self.loadTodayEvents()
        self.whatIsList = self.crawl_what_is_list()
        # self.sun = self.loadTodaySun()
        self.log.debug(f"{self.tag}Modul Today updated")