use bevy_app::{App, RunMode, ScheduleRunnerPlugin};
use bevy_ecs::message::{Message, MessageReader};
use bevy_tokio_tasks::TokioTasksPlugin;
use tokio_xmpp::Stanza;
use xmpp::component::resource::{ComponentConfig, XmppComponent};
use xmpp::component::{StanzaMatcher, StanzaMatcherPlugin};

#[derive(Message)]
struct TestMessage {
    content: String,
}

#[derive(Clone)]
struct TestMatcher;

impl StanzaMatcher for TestMatcher {
    type Message = TestMessage;

    fn matches(&mut self, candidate: &Stanza) -> Option<Self::Message> {
        match candidate {
            Stanza::Message(msg) => {
                let body = msg.bodies.get("")?.clone();
                Some(TestMessage { content: body })
            }
            _ => None,
        }
    }
}

fn log_test_messages(mut messages: MessageReader<TestMessage>) {
    for msg in messages.read() {
        println!("Received message: {}", msg.content);
    }
}

fn main() {
    println!("finished connecting");

    App::new()
        .add_plugins(ScheduleRunnerPlugin {
            run_mode: RunMode::Loop { wait: None },
        })
        .add_plugins(TokioTasksPlugin::default())
        .add_plugins(StanzaMatcherPlugin::new().matcher(TestMatcher))
        .init_resource::<ComponentConfig>()
        .init_resource::<XmppComponent>()
        .add_systems(bevy_app::Update, log_test_messages)
        .run();
}
