import logging
from datetime import date
from typing import Optional

from src.ezgg_lan_manager.services.DatabaseService import DatabaseService
from src.ezgg_lan_manager.types.News import News

logger = logging.getLogger(__name__.split(".")[-1])

class NewsService:
    def __init__(self, db_service: DatabaseService) -> None:
        self._db_service = db_service

    async def add_news(self, news: News) -> None:
        if news.news_id is not None:
            logger.warning("Can not add news with ID, ignoring...")
            return
        await self._db_service.add_news(news)

    async def get_news(self, dt_start: Optional[date] = None, dt_end: Optional[date] = None, newest_first: bool = True) -> list[News]:
        if not dt_end:
            dt_end = date.today()
        if not dt_start:
            dt_start = date(1900, 1, 1)
        fetched_news = await self._db_service.get_news(dt_start, dt_end)
        return sorted(fetched_news, key=lambda news: news.news_date, reverse=newest_first)

    async def update_news(self, news: News) -> None:
        return await self._db_service.update_news(news)

    async def delete_news(self, news_id: int) -> None:
        return await self._db_service.remove_news(news_id)

    async def get_latest_news(self) -> Optional[News]:
        try:
            all_news = await self.get_news(None, date.today())
            return all_news[0]
        except IndexError:
            logger.debug("There are no news to fetch")
