//! Compatibility path for peers that only support the original game-list protocol.

use std::{net::SocketAddr, sync::Arc, time::Duration};

use tokio::sync::{RwLock, mpsc::UnboundedSender};

use crate::{
    PeerEvent,
    events,
    network::fetch_games_from_peer,
    peer_db::PeerGameDB,
    remote_peer::update_peer_from_game_list,
};

pub(super) async fn request_games_from_peer(
    peer_addr: SocketAddr,
    tx_notify_ui: UnboundedSender<PeerEvent>,
    peer_game_db: Arc<RwLock<PeerGameDB>>,
) -> eyre::Result<()> {
    let mut retry_count = 0;

    loop {
        let games = fetch_games_from_peer(peer_addr).await?;
        log::info!("Received {} games from peer {peer_addr}", games.len());

        if games.is_empty() && retry_count < 1 {
            log::info!("Received 0 games from peer {peer_addr}, scheduling retry in 5s");
            tokio::time::sleep(Duration::from_secs(5)).await;
            retry_count += 1;
            continue;
        }

        let aggregated_games = update_peer_from_game_list(&peer_game_db, peer_addr, &games).await;
        events::send(&tx_notify_ui, PeerEvent::ListGames(aggregated_games));
        return Ok(());
    }
}
