import datetime
from aiogram.dispatcher.middlewares.base import BaseMiddleware
from aiogram.types import TelegramObject, Message, CallbackQuery, Update
from typing import Callable, Awaitable, Dict, Any


class AntiFloodMiddleware(BaseMiddleware):
    time_updates: dict[int, datetime.datetime] = {}
    timedelta_limiter: datetime.timedelta = datetime.timedelta(seconds=1)

    async def __call__(
            self,
            handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
            event: TelegramObject,
            data: Dict[str, Any],
    ) -> Any:
        if isinstance(event, Update):
            if event.callback_query:
                user_id = event.callback_query.from_user.id

                current_time = datetime.datetime.utcnow()  

                if user_id in self.time_updates:
                    last_update_time = self.time_updates[user_id]
                    if (current_time - last_update_time) < self.timedelta_limiter:
                        print('Flood detected')
                        await event.bot.answer_callback_query(
                            event.callback_query.id,
                            text="AntiFlood System",
                            show_alert=True
                        )
                        return  

                self.time_updates[user_id] = current_time
            return await handler(event, data)
        return await handler(event, data)  

