use serde::{Deserialize, Serialize};
use reqwest::blocking::ClientBuilder;
use super::define::*;
use super::myfs::*;

#[derive(Serialize, Deserialize, Debug)]
pub struct Req {
    pub topic: String,
    pub data: String,
    pub timeout: i64,
}

impl Req {
    pub fn init_from_order( top:&str,ord: &Order) -> Self {
        let time = *REQ_DURATION as i64;
        let s = serde_json::to_string(ord).unwrap_or("".to_string());
        Req {
            topic: top.to_string(),
            data: s,
            timeout: time,
        }
    }
    pub fn req_post_json(&self) -> anyhow::Result<Order> {
        let host=get_dot_env("PASS_URL");
        let url = format!("{}{}", host, API_REQ);
        let body = json!(&self);
        let res = ClientBuilder::new()
            .danger_accept_invalid_certs(true)
            .no_proxy()
            .build()
            .and_then(|c| c.post(&url).json(&body).send())?;
        let res1 = res.text()?;

        let res2: Order = serde_json::from_str(&res1)?;
        Ok(res2)
    }
    pub fn hb_ord(top:&str) -> anyhow::Result<Order> {

        let host=get_dot_env("PASS_URL");
        let url = format!("{}{}/{}", host, API_HB,top);
        let res=reqwest::blocking::get(&url)?;
        let res1=res.text()?;
        let res2:Order=serde_json::from_str(&res1)?;
        Ok(res2)
    }

}


#[derive(Serialize, Deserialize, Debug)]
pub struct Resp {
    pub topic: String,
    pub answer: String,
}
impl Resp{
    pub fn feed_back(res:&str)-> anyhow::Result<()> {
        let resp=Resp{
            topic:TOPIC_ALL.to_owned(),
            answer:res.to_owned(),
        };
        let host=get_dot_env("PASS_URL");
        let url = format!("{}{}", host, API_RESP);
        let body = json!(resp);
        ClientBuilder::new()
            .danger_accept_invalid_certs(true)
            .no_proxy()
            .build()
            .and_then(|c| c.post(&url).json(&body).send())?;
        Ok(())
    }
}