speedtest-tui 0.1.1

A terminal-based network speed test tool with real-time gauges and graphs
use async_trait::async_trait;

use super::{Provider, ServerInfo};

pub struct CustomProvider {
    download_url: String,
    upload_url: String,
}

impl CustomProvider {
    pub fn new(download_url: String, upload_url: String) -> Self {
        Self {
            download_url,
            upload_url,
        }
    }
}

#[async_trait]
impl Provider for CustomProvider {
    fn name(&self) -> &str {
        "Custom"
    }

    fn get_download_url(&self) -> String {
        self.download_url.clone()
    }

    fn get_upload_url(&self) -> String {
        self.upload_url.clone()
    }

    fn get_ping_url(&self) -> String {
        // Use the download URL base for ping
        self.download_url
            .split('/')
            .take(3)
            .collect::<Vec<_>>()
            .join("/")
    }

    async fn get_servers(&self) -> anyhow::Result<Vec<ServerInfo>> {
        Ok(vec![ServerInfo {
            id: "custom".to_string(),
            name: "Custom Server".to_string(),
            location: "Custom".to_string(),
            country: "".to_string(),
            host: self.get_ping_url(),
            latency_ms: None,
        }])
    }

    async fn select_best_server(&self) -> anyhow::Result<Option<ServerInfo>> {
        let ping_url = self.get_ping_url();
        let latency = crate::network::ping::single_ping(&ping_url).await.ok();

        Ok(Some(ServerInfo {
            id: "custom".to_string(),
            name: "Custom Server".to_string(),
            location: "Custom".to_string(),
            country: "".to_string(),
            host: ping_url,
            latency_ms: latency,
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_custom_provider() {
        let provider = CustomProvider::new(
            "http://localhost:8080/download".to_string(),
            "http://localhost:8080/upload".to_string(),
        );

        assert_eq!(
            provider.get_download_url(),
            "http://localhost:8080/download"
        );
        assert_eq!(provider.get_upload_url(), "http://localhost:8080/upload");
        assert_eq!(provider.get_ping_url(), "http://localhost:8080");
    }
}