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::dyn_dispatch::{Dispatch, Slave_Nat, Slave_Pass};
use super::restart::cmd_restart;
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");
}


fn select_dispatch() -> Box<dyn Dispatch> {
    let method = get_dot_env("TRANS");
    if method == "pass".to_string() {
        return Box::new(Slave_Pass {});
    }
    Box::new(Slave_Nat {})
}

pub fn dispatch() {
    print!("slave begin to work\n");

    let method = get_dot_env("TRANS");
    // nats restart走sub pub
    if method == "nats".to_string() {
        std::thread::spawn(|| {
            cmd_restart();
        });
    }

    let d = select_dispatch();
    loop {
        match d._dispatch() {
            Ok(()) => print!("success one round\n"),
            Err(e) => {
                let res = format!("fail round{}\n", e);
            }
        }
    }
}



pub fn reply_order(ord: Order) -> Order {
    let mut slave1 = ord.clone();
    if let Err(e) = parse_input(&ord.req) {
        slave1.status = FAIL.to_owned();
        slave1.resp = format!("parse command error:{}", e);
        return slave1;
    }


    let (cmd, args) = parse_input(&slave1.req).unwrap();
    dbg!(&cmd);

    let method = get_dot_env("TRANS");

    if method=="pass".to_string(){
        let _cmd=cmd.clone();
        if _cmd==CMD_RESTART{
              system_shutdown::reboot();
        }

    }


    match cmd.as_str() {
        CMD_CD if args.len() == 1 => cmd_cd(&slave1),
        CMD_SEND => cmd_send(&slave1),
        CMD_REC => cmd_receive(&slave1),
        _ if slave1.wait => other_sync_cmd(&slave1),
        _ => {
            let a = other_async_cmd(&slave1);
            res2order(a, &slave1)
        }
    }
}
