use crate::arg::get_arg;
use crate::serdejson::JsonVExentd;
use crate::{IResult, JsonV};

#[must_use]
pub fn send_message(body_str: impl AsRef<str>) -> IResult {
    let body_str = body_str.as_ref();
    let msg_type = &get_arg("mail.subject").as_string2().unwrap_or_else(|| "未定义主题".to_owned());
    let url = match get_arg("mail.feishu_url") {
        JsonV::String(v) => v,
        _ => return Ok(()),
    };
    send(msg_type, url, body_str)
}

#[must_use]
pub fn send(subject: impl AsRef<str>, url: impl AsRef<str>, body_str: impl AsRef<str>) -> IResult {
    let body_str = body_str.as_ref();
    let msg_type = subject.as_ref();
    let url = url.as_ref();
    let msg = format!("[{}]\n{}", msg_type, body_str).replace('"', "'");
    let msg = serde_json::json!({"msg_type":"text","content":{"text": msg}});
    let r = crate::req::post_json::<JsonV>(url.to_string(), msg).map_err(|e| format!("feishu request error: {:?}", e))?;
    if r["code"].as_i64().unwrap_or_default() != 0 {
        Err(format!("feishu error response: {:?}", r))?;
    }
    Ok(())
}

#[must_use]
pub fn send_arr_message(body_str: &Vec<String>) -> IResult {
    let mut content = String::default();
    for x in body_str {
        content.push_str("\n");
        content.push_str(x);
    }
    let content = content.trim_start_matches("\n");
    send_message(content)
}
