use crate::common::define::{
    Order, CMD_RESTART, REQ_DURATION, TOPIC_ALL, TOPIC_RESTART,  API_REQ
};
use crate::common::myfs::get_dot_env;
lazy_static! {
    pub static ref NATS_URL:String =get_dot_env("NATS_URL");
    pub static ref NATS_ACCOUNT:String =get_dot_env("NATS_ACCOUNT");
    pub static ref NATS_PWD:String =get_dot_env("NATS_PWD");
    pub static ref SLAVE_ID:String=get_dot_env("SLAVE_ID");
}

pub fn cmd_restart() {
    loop {
        match _cmd_restart() {
            Ok(()) => print!("success one restart\n"),
            Err(e) => {
                let res = format!("fail restart{}\n", e);
            }
        }
    }
}

fn _cmd_restart() -> anyhow::Result<()> {
    let nc = nats::ConnectionOptions::new()
        .with_name("remote restart")
        .with_user_pass(&NATS_ACCOUNT, &NATS_PWD)
        .connect(&NATS_URL)?;

    let sub = nc.subscribe(&TOPIC_RESTART)?;
    for msg in sub.messages() {
        let str = std::str::from_utf8(&msg.data)?;
        let ord: Order = serde_json::from_str(str)?;
        if ord.slave.clone() == SLAVE_ID.to_string() {
            system_shutdown::reboot()?;
        }
    }
    Ok(())
}
