from telebot.types import Message, CallbackQuery

from app.bot.keyboards.active_triggers import create_region_keyboard
from app.bot.utils.regions import get_sorted_regions_plain
from app.bot.processors.active_triggers_processor import (
    process_region_selection,
    process_group_selection,
    process_all_groups_request,
)


def register_active_triggers(bot, app, state_manager):
    @bot.message_handler(commands=['active_triggers'])
    @bot.message_handler(func=lambda m: m.text == "Активные проблемы")
    def handle_active_triggers(message: Message):
        with app.app_context():
            regions = get_sorted_regions_plain()
            markup = create_region_keyboard(regions, 0)
            bot.send_message(message.chat.id, "Выберите регион для получения активных событий:", reply_markup=markup)

def register_callbacks_active_triggers(bot,app,state_manager):
    @bot.callback_query_handler(func=lambda c: c.data.startswith("region_"))
    def region_selected(callback_query: CallbackQuery):
        region_id = callback_query.data.split("_")[1]
        process_region_selection(callback_query.message.chat.id,bot, region_id)

    @bot.callback_query_handler(func=lambda c: c.data.startswith("group_"))
    def group_selected(callback_query: CallbackQuery):
        group_id = callback_query.data.split("_")[1]
        process_group_selection(callback_query.message.chat.id,bot, group_id)

    @bot.callback_query_handler(func=lambda c: c.data.startswith("all_groups_"))
    def all_groups_selected(callback_query: CallbackQuery):
        region_id = callback_query.data.split("_")[2]
        process_all_groups_request(callback_query.message.chat.id,bot, region_id)

    @bot.callback_query_handler(func=lambda c: c.data.startswith("regions_page_"))
    def regions_page_selected(callback_query: CallbackQuery):
        page = int(callback_query.data.split("_")[-1])
        with app.app_context():
            regions = get_sorted_regions_plain()
            markup = create_region_keyboard(regions, page)
            bot.edit_message_reply_markup(
                chat_id=callback_query.message.chat.id,
                message_id=callback_query.message.message_id,
                reply_markup=markup
            )
        bot.answer_callback_query(callback_query.id)  # обязательно, чтобы убрать "часики"

