use crate::common::define::{
    Order, CMD_RESTART, NATS_ACCOUNT, NATS_PWD, NATS_URL, REQ_DURATION, TOPIC_ALL, TOPIC_RESTART,
};

pub fn _send_order(ord: &Order) -> anyhow::Result<Order> {
    let nc = nats::ConnectionOptions::new()
        .with_name("remote shell")
        .with_user_pass(&NATS_ACCOUNT, &NATS_PWD)
        .connect(&NATS_URL)?;
    let input = serde_json::to_string(ord)?;
    let resp = nc.request_timeout(
        &TOPIC_ALL,
        input,
        std::time::Duration::from_secs(*REQ_DURATION + 5),
    )?;
    let str = std::str::from_utf8(&resp.data)?;
    let res = serde_json::from_str(str)?;
    Ok(res)
}

pub fn send_order(ord: &Order) -> Order {
    let res = _send_order(ord);
    match res {
        Ok(o) => o,
        Err(e) => {
            let mut res = ord.clone();
            res.resp = format!("发送失败:{}", e);
            res
        }
    }
}

pub fn pub_restart(slave: &str) {
    match _pub_restart(slave) {
        Ok(()) => {
            println!("发送成功");
        }
        Err(e) => {
            let res = format!("发送失败:{}", e);
            println!("{}", res);
        }
    }
}

pub fn _pub_restart(slave: &str) -> anyhow::Result<()> {
    let nc = nats::ConnectionOptions::new()
        .with_name("remote restart")
        .with_user_pass(&NATS_ACCOUNT, &NATS_PWD)
        .connect(&NATS_URL)?;
    let  ord = Order::new_from_host(CMD_RESTART, &slave);
    let input = serde_json::to_string(&ord)?;
    nc.publish(&TOPIC_RESTART, input)?;
    Ok(())
}


