# Path: src/bot/handler/FilterableHandler.py
# class FilterableHandler(Handler):
# 
#     def __init__(self):
#         self._filters = []  # type: List[HandlerFilter]
#         self._keys_map = {}
#         super().__init__(None)
# 
#     def add_filter(self, handler_filter: HandlerFilter, key: str = None):
#         self._filters.append(handler_filter)
#         if key:
#             index = len(self._filters) - 1
#             self._keys_map[key] = index
#         return self
# 
#     def add_filters(self, handler_filters: List[HandlerFilter]):
#         for f in handler_filters:
#             self.add_filter(f)
#         return self
# 
#     def remove_filter(self, key: str):
#         if key in self._keys_map:
#             self._filters.pop(self._keys_map[key])
#         else:
#             raise RuntimeError('No filter with key: {0} founded.')
# 
#     def clear_filters(self):
#         self._filters.clear()
#         self._keys_map.clear()
#         return self
# 
#     def check_update(self, update: Update):
#         result = False
#         if len(self._filters) > 0 and isinstance(update, Update) and (update.message or update.edited_message):
#             tg_message = update.message or update.edited_message
#             user_id = update.message.chat_id
#             message = Message(tg_message.text, user_id)
#             i = 0
#             result = True
#             while result and i < len(self._filters):
#                 result = self._filters[i].filter(message)
#                 i = i + 1
# 
#         return result


import telegram
from injector import inject
from telegram import Update
from telegram.ext import Dispatcher
from telegram.utils.helpers import escape_markdown
from bot.handler.decorator.TypingDecorator import typing
from .FilterableHandler import FilterableHandler
from bot.handler.filter import RegexFilter
from booking.usecase import EventsUseCase, ClassroomsUseCase
from booking.scheduler import Scheduler, SchedulerStatus
    @typing
    def handle_update(self, update: Update, dispatcher: Dispatcher):
        chat_id = update.message.chat_id
        class_name = update.message.text  # type: str
        if class_name.startswith('/'):
            class_name = class_name[1:]
        class_name = class_name.lower()
        events = self._events_uc.get_today_events(self._classrooms_map[class_name])
        message = "*Classroom: {0}*\n\n".format(class_name.upper())
        if len(events) > 0:
            for event in events:
                event_name = event.get_name().replace('*', '')
                message += "*{0}*\nBegin at: {1}\nEnd at: {2}\n\n".format(event_name,
                                                                          event.get_begin().strftime("%H:%M"),
                                                                          event.get_end().strftime("%H:%M"))
        else:
            message += "No scheduled events"
        dispatcher.bot.send_message(chat_id=chat_id, text=message, parse_mode=telegram.ParseMode.MARKDOWN)
        return True

    def on_scheduler_status_changed(self, new_status: SchedulerStatus):
        if new_status != SchedulerStatus.COMPLETED:
            self.clear_filters()
            self._classrooms_map.clear()
        else:
            classrooms = []
            for classroom in self._classrooms_uc.get_classrooms():
                classroom_name = classroom.get_name().lower()
                self._classrooms_map[classroom_name] = classroom.get_identifier()
                classrooms.append(classroom_name)

# Path: src/bot/handler/FilterableHandler.py
# class FilterableHandler(Handler):
# 
#     def __init__(self):
#         self._filters = []  # type: List[HandlerFilter]
#         self._keys_map = {}
#         super().__init__(None)
# 
#     def add_filter(self, handler_filter: HandlerFilter, key: str = None):
#         self._filters.append(handler_filter)
#         if key:
#             index = len(self._filters) - 1
#             self._keys_map[key] = index
#         return self
# 
#     def add_filters(self, handler_filters: List[HandlerFilter]):
#         for f in handler_filters:
#             self.add_filter(f)
#         return self
# 
#     def remove_filter(self, key: str):
#         if key in self._keys_map:
#             self._filters.pop(self._keys_map[key])
#         else:
#             raise RuntimeError('No filter with key: {0} founded.')
# 
#     def clear_filters(self):
#         self._filters.clear()
#         self._keys_map.clear()
#         return self
# 
#     def check_update(self, update: Update):
#         result = False
#         if len(self._filters) > 0 and isinstance(update, Update) and (update.message or update.edited_message):
#             tg_message = update.message or update.edited_message
#             user_id = update.message.chat_id
#             message = Message(tg_message.text, user_id)
#             i = 0
#             result = True
#             while result and i < len(self._filters):
#                 result = self._filters[i].filter(message)
#                 i = i + 1
# 
#         return result


# Path: src/bot/handler/ClassRoomEventHandler.py
import telegram
from injector import inject
from telegram import Update
from telegram.ext import Dispatcher
from telegram.utils.helpers import escape_markdown
from bot.handler.decorator.TypingDecorator import typing
from .FilterableHandler import FilterableHandler
from bot.handler.filter import RegexFilter
from booking.usecase import EventsUseCase, ClassroomsUseCase
from booking.scheduler import Scheduler, SchedulerStatus

    @typing
    def handle_update(self, update: Update, dispatcher: Dispatcher):
        chat_id = update.message.chat_id
        class_name = update.message.text  # type: str
        if class_name.startswith('/'):
            class_name = class_name[1:]
        class_name = class_name.lower()
        events = self._events_uc.get_today_events(self._classrooms_map[class_name])
        message = "*Classroom: {0}*\n\n".format(class_name.upper())
        if len(events) > 0:
            for event in events:
                event_name = event.get_name().replace('*', '')
                message += "*{0}*\nBegin at: {1}\nEnd at: {2}\n\n".format(event_name,
                                                                          event.get_begin().strftime("%H:%M"),
                                                                          event.get_end().strftime("%H:%M"))
        else:
            message += "No scheduled events"
        dispatcher.bot.send_message(chat_id=chat_id, text=message, parse_mode=telegram.ParseMode.MARKDOWN)
        return True

    def on_scheduler_status_changed(self, new_status: SchedulerStatus):
        if new_status != SchedulerStatus.COMPLETED:
            self.clear_filters()
            self._classrooms_map.clear()
        else:
            classrooms = []
            for classroom in self._classrooms_uc.get_classrooms():
                classroom_name = classroom.get_name().lower()
                self._classrooms_map[classroom_name] = classroom.get_identifier()
                classrooms.append(classroom_name)

            self.add_filter(RegexFilter(classrooms, case_sensitive=False, handle_command=True))