use crate::ui::prelude::*;
use super::*;

pub fn schema(
) -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>> {
    let menu_commands_handler = dptree::entry().branch(
        Message::filter_text()
            .branch(
                filter_localized_text!(Ru, "🎫Создать для Траффика")
                    .endpoint(create_traffic_promo_help_message),
            )
            .branch(
                filter_localized_text!(Ru, "💯Создать для Скидки")
                    .endpoint(add_discount_promo_handler),
            )
            .branch(
                filter_localized_text!(Ru, "🗑️Удалить промокоды")
                    .endpoint(delete_promos_handler),
            )
            .branch(
                filter_localized_text!(Ru, "💸Cтоимость")
                    .endpoint(change_price_handler),
            )
            .branch(
                filter_localized_text!(Ru, "💳 Платаёжные системы")
                    .endpoint(show_payment_systems_menu),
            )
            .branch(
                filter_localized_text!(Ru, "📈 Статистика")
                    .endpoint(stats_handler),
            )
            .branch(
                filter_localized_text!(Ru, "💾 Бекап")
                    .endpoint(backup_handler),
            )
            .branch(
                filter_localized_text!(Ru, "🔙 Назад в панель")
                    .endpoint(admin_entrypoint),
            )
            .branch(
                filter_localized_text!(Ru, "🎫 Промокоды")
                    .endpoint(show_promo_menu),
            )
            .branch(
                filter_localized_text!(Ru, "🚩 Баннеры")
                    .endpoint(show_banner_menu),
            )
            .branch(
                filter_localized_text!(Ru, "⚙️ Настройки")
                    .endpoint(show_preferences_menu),
            )
            .branch(
                filter_localized_text!(Ru, "⚙️Реферальный %")
                    .endpoint(change_referral_percent_handler),
            )
            .branch(
                filter_localized_text!(Ru, "📖 Разработка")
                    .endpoint(show_development_blog),
            )
            .branch(
                filter_localized_text!(Ru, "‍🤝‍ Ссылки")
                    .endpoint(show_source_links),
            )
            .branch(
                filter_localized_text!(Ru, "📢 Рассылка")
                    .endpoint(show_broadcast_menu),
            )
            .branch(
                filter_localized_text!(Ru, "💳 Заявки на вывод")
                    .endpoint(show_withdraw_requests),
            ),
    );

    use dptree::case;
    let message_handler = Update::filter_message()
        .branch(menu_commands_handler)
        .branch(case_expr![MasterState { admin_kind: AdminStateKind::Menu, .. }])
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::StatsReceiveUserId { .. }, .. }]
                .endpoint(stats_receive_user_id_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::StatsReceivePool { user_id }, .. } => user_id]
                .endpoint(user_stats_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::StatsReceivePeriod, .. }]
                .endpoint(stats_period_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::ReceivePoolPrice { pool_type }, .. } => pool_type]
                .endpoint(receive_pool_price_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::DeletePromos { page }, .. } => page]
                .endpoint(delete_promos_state_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::SourceLinks { page, search_query }, .. } => (page, search_query)]
                .endpoint(source_links_state_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::CreateSourceLink, .. } => ()]
                .endpoint(create_source_link_state_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::CreateSourceLinkWithCode { ref_code }, .. } => ref_code]
                .endpoint(create_source_link_with_code_state_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::PaymentSystemEditDescription { name }, .. } => name]
                .endpoint(handle_payment_system_description_input),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::Broadcast { users_without_purchases }, .. } => users_without_purchases]
                .endpoint(handle_broadcast_text_input),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::BroadcastConfirm { users_without_purchases, broadcast_text }, .. } => (users_without_purchases, broadcast_text)]
                .endpoint(broadcast_confirm_state_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::WithdrawRequests { page, search_query }, .. } => (page, search_query)]
                .endpoint(withdraw_requests_state_handler),
        )
        .branch(
            case_expr![MasterState { admin_kind: AdminStateKind::ReceiveTrafficAmount { user_id }, .. } => user_id]
                .endpoint(receive_traffic_amount),
        )
        .chain(
            Update::filter_message()
            .chain(
                Message::filter_text()
                .inspect(|text: String| println!("msg: {:?}", text))
                .branch(
                    case_expr![MasterState { admin_kind: AdminStateKind::AddTrafficReceiveAmount { user_id, pool }, .. } => (user_id, pool)]
                        .endpoint(add_traffic_receive_amount_handler),
                )
                .branch(
                    case_expr![MasterState { admin_kind: AdminStateKind::ReceiveReferralPercent, .. }]
                        .endpoint(receive_referral_percent_handler),
                )
                .branch(
                    case_expr![MasterState { admin_kind: AdminStateKind::ReceiveUserReferralPercent { user_id }, .. } => user_id]
                        .endpoint(receive_user_referral_percent_handler),
                )
                .branch(
                    case_expr![MasterState { admin_kind: AdminStateKind::WaitingForTranslation { .. }, .. }]
                        .endpoint(handle_translation_input),
                )
            )
        );

    let command_handler = Update::filter_message()
        .filter_command::<Command>()
        .branch(case![Command::Promo].endpoint(admin_promo_handler))
        .branch(case![Command::Profile].endpoint(profile_command_handler))
        .branch(case![Command::Stats].endpoint(stats_command_handler))
        .branch(case![Command::Load(target)].endpoint(load_handler))
        .branch(case![Command::FixI18n].endpoint(fix_i18n_handler));

    let callback_handler = Update::filter_callback_query()
        .filter(|q: CallbackQuery| {
            if let Some(data) = q.data {
                serde_json::from_str::<AdminCallback>(&data).is_ok()
            } else {
                false
            }
        })
        .endpoint(callback_handler);

    admin_filter_async().chain(
      case_expr![MasterState { kind: MasterStateKind::Admin, .. }]
        .branch(command_handler)
        .branch(message_handler)
        .branch(callback_handler)
    )
}
