/// Connects to the "server" example. Have the server example running when you're running this example.

use dbus::arg;

// First, let's autogenerate some code using the dbus-codegen-rust tool.
// With the server example running, the below was (part of) the output when running:
// `dbus-codegen-rust -d com.example.dbustest -p /hello -m None`

#[derive(Debug)]
pub struct ComExampleDbustestHelloHappened {
    pub sender: String,
}

impl arg::AppendAll for ComExampleDbustestHelloHappened {
    fn append(&self, i: &mut arg::IterAppend) {
        arg::RefArg::append(&self.sender, i);
    }
}

impl arg::ReadAll for ComExampleDbustestHelloHappened {
    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
        Ok(ComExampleDbustestHelloHappened {
            sender: i.read()?,
        })
    }
}

impl dbus::message::SignalArgs for ComExampleDbustestHelloHappened {
    const NAME: &'static str = "HelloHappened";
    const INTERFACE: &'static str = "com.example.dbustest";
}

// Autogenerated code ends here.

use dbus::blocking::Connection;
use dbus::Message;
use std::error::Error;
use std::time::Duration;


fn main() -> Result<(), Box<dyn Error>> {
    // Let's start by starting up a connection to the session bus.
    let c = Connection::new_session()?;

    {
        let proxy = c.with_proxy("com.example.dbustest", "/hello", Duration::from_millis(5000));

        // Let's start listening to signals.
        let _id = proxy.match_signal(|h: ComExampleDbustestHelloHappened, _: &Connection, _: &Message| {
            println!("Hello happened from sender: {}", h.sender);
            true
        });

        // Say hello to the server example, so we get a signal.
        let (s,): (String,) = proxy.method_call("com.example.dbustest", "Hello", ("match_signal example",))?;
        println!("{}", s);
    }

    // Listen to incoming signals forever.
    loop { c.process(Duration::from_millis(1000))?; }
}
