use rumqttc::{Client, Connection, MqttOptions, QoS};
use std::{env, time::Duration};

pub fn init_cli() -> (Client, Connection) {
    let mut mqttoptions =
        MqttOptions::new("test-1", env::var("MQTT_HOST").unwrap().to_string(), 1883);
    mqttoptions.set_keep_alive(Duration::from_secs(1));
    let (client, connection) = Client::new(mqttoptions, 10);

    (client, connection)
}

pub fn publish_message(mut client: Client, topic: &str, payload: String) -> Client {
    client
        .publish(get_topic_name(topic), QoS::AtLeastOnce, true, payload)
        .unwrap();
    client
}

pub fn disconnect(mut connection: Connection, count: usize) {
    // Disconnect from the broker.
    for (i, notification) in connection.iter().enumerate() {
        match notification {
            Ok(notif) => {
                println!("{i}. Notification = {notif:?}");
                if i > count {
                    return;
                }
            }
            Err(error) => {
                println!("{i}. Notification ERROR = {error:?}");
                return;
            }
        }
    }
}

pub fn get_topic_name(types: &str) -> String {
    let mut topic = env::var("SERVICE").unwrap().to_string();
    topic.push('/');
    let capteur = env::var("CAPTEUR").unwrap().to_string();
    topic.push_str(&capteur);
    topic.push('/');
    topic.push_str(&types);

    topic
}
