//! Basic example of using cfgmatic-reactive.
//!
//! Demonstrates:
//! - Creating a Dispatcher
//! - Registering handlers
//! - Subscribing to configuration paths
//! - Dispatching events

use cfgmatic_reactive::prelude::*;

/// A simple handler that logs events.
struct LoggingHandler {
    id: HandlerId,
    name: String,
}

impl LoggingHandler {
    /// Creates a new logging handler.
    fn new(name: &str) -> Self {
        Self {
            id: HandlerId::new(format!("logging-{name}")),
            name: name.to_string(),
        }
    }
}

impl Handler for LoggingHandler {
    fn id(&self) -> &HandlerId {
        &self.id
    }

    fn handle(&self, event: &Event) -> Result<()> {
        println!(
            "[{}] Event: {:?} at path '{}'",
            self.name, event.kind, event.path
        );
        Ok(())
    }
}

fn main() -> Result<()> {
    // Create a dispatcher
    let dispatcher = Dispatcher::new();

    // Register handlers
    let handler1 = LoggingHandler::new("main");
    let handler2 = LoggingHandler::new("backup");

    dispatcher.register_handler(handler1)?;
    dispatcher.register_handler(handler2)?;

    println!("Registered {} handlers", dispatcher.handler_count());

    // Create subscriptions
    let sub1 = Subscription::file("/config/app.toml");
    let sub2 = Subscription::file("/config/database.json");

    dispatcher.subscribe(sub1)?;
    dispatcher.subscribe(sub2)?;

    println!("Active subscriptions: {}", dispatcher.subscription_count());

    // Dispatch an event
    let event = Event::change("/config/app.toml");
    dispatcher.dispatch(&event)?;

    // Create different event types
    let update_event = Event::new(
        EventKind::Update,
        "/config/database.json",
        EventMetadata::new("file-watcher"),
    );
    dispatcher.dispatch(&update_event)?;

    println!("\nDispatched 2 events successfully");

    Ok(())
}
