use crate::Exception;
use std::collections::HashMap;
use url::Url;
use urlencoding::{decode, encode};

/// URL utility class, for extracting parameters, URL encoding and decoding, etc.
pub struct UrlUtil;

impl UrlUtil {

    /// 对URL进行编码处理
    pub fn url_encode(url: &str) -> Result<String, Exception> {
        let original_url = url;
        // 解析原始 URL
        let parsed_url = Url::parse(original_url)?;
        Ok(parsed_url.to_string())
    }

    /// 从URL中提取查询参数并返回HashMap
    pub fn parameters(url: &str) -> Result<HashMap<String, String>, Exception>{
        let parsed_url = Url::parse(url)?;
        let params: HashMap<String, String> = parsed_url.query_pairs()
            .into_owned()  // 将 &str 转换为 String（避免生命周期问题）
            .collect();
        Ok(params)
    }

    /// 对输入字符串进行URL编码处理
    pub fn encode(str: &str) -> String {
        encode(str).to_string()
    }

    /// 对输入字符串进行URL解码处理
    pub fn decode(str: &str) -> String {
        decode(str).unwrap().to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_url_encode() {
        // TODO 测试未通过
        let url = "https://www.baidu.com/s?wd=hello world";
        let result = UrlUtil::url_encode(url).unwrap();
        println!("{}", result);
        assert_eq!(result, "https://www.baidu.com/s?wd=hello%20world");
    }
    #[test]
    fn test_encode() {
        let str = "hello world";
        let result = UrlUtil::encode(str);
        println!("{}", result);
    }
}
