pub use crate::miner::Connection;
use async_std::sync::{Arc, RwLock};
use log::info;
use std::collections::HashMap;
use std::net::SocketAddr;
use stratum_types::traits::{StratumManager, StratumParams};
use stratum_types::Result;

#[derive(Default)]
pub struct MinerList<SM: StratumManager> {
    pub miners: RwLock<HashMap<SocketAddr, Arc<Connection<SM>>>>,
}

impl<SM> MinerList<SM>
where
    SM: StratumManager,
{
    pub fn new() -> Self {
        MinerList {
            miners: RwLock::new(HashMap::new()),
        }
    }

    pub async fn add_miner(&self, addr: SocketAddr, miner: Arc<Connection<SM>>) -> Result<()> {
        self.miners.write().await.insert(addr, miner);
        Ok(())
    }

    pub async fn remove_miner(&self, addr: SocketAddr) -> Result<()> {
        self.miners.write().await.remove(&addr);
        Ok(())
    }

    pub async fn broadcast_new_job(&self) -> Result<()> {
        let miners = self.miners.read().await;

        info!("Broadcasting new work to miners.");

        // let handles = my_futures.into_iter().map(async_std::task::spawn).collect::<Vec<_>>();
        // let results = futures::future::join_all(handles).await;

        let mut results = Vec::new();

        for miner in miners.values() {
            info!("Sending new work to miner: {}", miner.id);
            // let miner_clone = miner.clone();
            // let miner = miner.clone();
            // results.push(async_std::task::spawn(async move {
            results.push(miner.send_work());
            // Block here until this done.
            // miner.send_work().await;
            // }));
        }

        futures::future::join_all(results).await;
        info!("All work send to miners");

        Ok(())
    }

    pub async fn get_all_miners(&self) -> Vec<Arc<Connection<SM>>> {
        self.miners
            .read()
            .await
            .values()
            .map(|x| x.clone())
            .collect()
    }
}
