import logging
from asyncio import sleep
from datetime import datetime
from time import strptime

from rio import Column, Component, event, TextStyle, Text

from src.ezgg_lan_manager import ConfigurationService, UserService
from src.ezgg_lan_manager.components.MainViewContentBox import MainViewContentBox
from src.ezgg_lan_manager.components.NewsPost import EditableNewsPost
from src.ezgg_lan_manager.services.NewsService import NewsService
from src.ezgg_lan_manager.types.News import News

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

class ManageNewsPage(Component):
    news_posts: list[News] = []
    show_success_message = False

    @event.on_populate
    async def on_populate(self) -> None:
        await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - News Verwaltung")
        self.news_posts = (await self.session[NewsService].get_news())[:8]

    async def on_new_news_post(self, post: EditableNewsPost) -> None:
        # @todo: For some reason, new posts do not appear through a force_refresh, only after visiting the page again
        author = await self.session[UserService].get_user(post.author)
        if author is None:
            logger.warning(f"Tried to set news post author to '{post.author}', which does not exist.")
            return
        await self.session[NewsService].add_news(News(
            news_id=None,
            title=post.title,
            subtitle=post.subtitle,
            content=post.text,
            author=author,
            news_date=strptime(post.date, "%d.%m.%Y"),
        ))
        self.news_posts = (await self.session[NewsService].get_news())[:8]
        self.show_success_message = True
        self.force_refresh()
        await sleep(3)
        self.show_success_message = False
        self.force_refresh()

    async def on_news_post_changed(self, post: EditableNewsPost) -> None:
        author = await self.session[UserService].get_user(post.author)
        if author is None:
            logger.warning(f"Tried to set news post author to '{post.author}', which does not exist.")
            return
        await self.session[NewsService].update_news(News(
            news_id=post.news_id,
            title=post.title,
            subtitle=post.subtitle,
            content=post.text,
            author=author,
            news_date=strptime(post.date, "%d.%m.%Y"),
        ))
        self.news_posts = (await self.session[NewsService].get_news())[:8]

    async def on_news_post_deleted(self, news_id: int) -> None:
        await self.session[NewsService].delete_news(news_id)
        self.news_posts = (await self.session[NewsService].get_news())[:8]

    def build(self) -> Component:
        posts = [EditableNewsPost(
            news_id=news.news_id,
            title=news.title,
            subtitle=news.subtitle,
            text=news.content,
            date=news.news_date.strftime("%d.%m.%Y"),
            author=news.author.user_name,
            save_cb=self.on_news_post_changed,
            delete_cb=self.on_news_post_deleted
        ) for news in self.news_posts]
        return Column(
            MainViewContentBox(
                Column(
                    Text(
                        text="News Verwaltung",
                        fill=self.session.theme.background_color,
                        style=TextStyle(
                            font_size=1.2
                        ),
                        margin_top=2,
                        margin_bottom=0,
                        align_x=0.5
                    ),
                    Text(
                        text="Neuen News Post erstellen",
                        fill=self.session.theme.background_color,
                        style=TextStyle(
                            font_size=1.1
                        ),
                        margin_top=2,
                        margin_bottom=0,
                        align_x=0.5
                    ),
                    EditableNewsPost(
                        title="",
                        subtitle="",
                        text="",
                        date=datetime.now().strftime("%d.%m.%Y"),
                        author="",
                        save_cb=self.on_new_news_post
                    ),
                    Text(
                        text="Post erfolgreich erstellt",
                        fill=self.session.theme.success_color,
                        style=TextStyle(
                            font_size=0.7 if self.show_success_message else 0
                        ),
                        margin_top=0.1,
                        margin_bottom=0,
                        align_x=0.5
                    ),
                    Text(
                        text="Bisherige Posts",
                        fill=self.session.theme.background_color,
                        style=TextStyle(
                            font_size=1.1
                        ),
                        margin_top=2,
                        margin_bottom=0,
                        align_x=0.5
                    ),
                    *posts
                )
            ),
            align_y=0
        )
