use futures_util::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use reqwest::Client;
use std::fs::File;
use std::io::Write;

/// 从url下载文件
pub async fn download_file(url: &str, path: &str) -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let response = client.get(url).send().await?;

    // 获取文件总大小（如果服务器提供）
    let total_size = response.content_length().unwrap_or(0);

    // 创建进度条
    //let pb = ProgressBar::new(total_size);

    let pb = ProgressBar::with_draw_target(
        Some(total_size),
        indicatif::ProgressDrawTarget::stdout_with_hz(20)
    );

    pb.set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")?
            .progress_chars("#>-"),
    );

    // 创建输出文件
    let mut file = File::create(path)?;
    let mut downloaded: u64 = 0;

    // 流式下载
    let mut stream = response.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        file.write_all(&chunk)?;

        downloaded += chunk.len() as u64;
        pb.set_position(downloaded);
    }

    pb.finish_with_message("下载完成");
    Ok(())
}

/// http/https请求获取远程数据
pub async fn http_get(url: &str) -> Result<String, Box<dyn std::error::Error>> {
    let client = Client::new();
    let response = client.get(url).send().await?;
    Ok(response.text().await?)
}
