use crate::common::define::*;
use crate::slave::slave_cmds::*;
use crate::common::define::{TOPIC_ALL};
use std::io::Write;
use std::io::stdout;
use crate::common::myfs::*;
use crate::slave::sync_cmd::other_sync_cmd;
use super::slave_dispatch::reply_order;
use crate::common::req_resp::{Req, Resp};
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 struct Slave_Pass {}

pub struct Slave_Nat {}

pub trait Dispatch {
    fn _dispatch(&self) -> anyhow::Result<()>;
}

impl Dispatch for Slave_Nat {
    fn _dispatch(&self) -> anyhow::Result<()> {
        let nc = nats::ConnectionOptions::new()
            .with_name("remote shell")
            .with_user_pass(&NATS_ACCOUNT, &NATS_PWD)
            .connect(&NATS_URL)?;

        let sub = nc.subscribe(&TOPIC_ALL)?;
        for msg in sub.messages() {
            let from_host = std::str::from_utf8(&msg.data)?;
            // 如果rec，file已经是b64
            let ord: Order = serde_json::from_str(from_host)?;
            if ord.slave.clone() == SLAVE_ID.to_string() {
                stdout().flush()?;


                // 处理主体
                let ord_from_slave = reply_order(ord.clone());
                // 处理主体

                let feedback = serde_json::to_string(&ord_from_slave)?;
                dbg!("send res\n");
                msg.respond(feedback)?;
                dbg!("send over\n ");
            }
        }
        Ok(())
    }


}


impl Dispatch for Slave_Pass {
    fn _dispatch(&self) -> anyhow::Result<()> {
        let ord = Req::hb_ord(TOPIC_ALL)?;
        dbg!(&ord);

        if ord.slave.clone() == SLAVE_ID.to_string() {
            stdout().flush()?;
            // 处理主体
            let ord_from_slave = reply_order(ord.clone());
            // 处理主体

            let feedback = serde_json::to_string(&ord_from_slave)?;
            Resp::feed_back(&feedback)?;
        }
        Ok(())
    }

}
