use std::time::Duration;

use avam_protocol::SimConnectPacket;
use tokio::{
    sync::broadcast::{Receiver, Sender},
    time::sleep,
};

use crate::state_machine::Event;

pub struct SimConnect {
    simconnect_receiver: Receiver<SimConnectPacket>, // Data from the socket
    socket_sender: Sender<SimConnectPacket>,         // Data to the socket
    sender: Sender<Event>,
    receiver: Receiver<Event>,
}

impl SimConnect {
    pub fn new(
        simconnect_receiver: Receiver<SimConnectPacket>,
        socket_sender: Sender<SimConnectPacket>,
        sender: Sender<Event>,
        receiver: Receiver<Event>,
    ) -> Self {
        Self {
            simconnect_receiver,
            socket_sender,
            sender,
            receiver,
        }
    }

    pub async fn run(&self) -> Result<(), anyhow::Error> {
        let mut receiver = self.receiver.resubscribe();
        loop {
            if let Ok(Event::Quit) = receiver.try_recv() {
                break;
            }

            // handle simconnect stuff here

            sleep(Duration::from_millis(100)).await;
        }

        Ok(())
    }
}

pub async fn start(
    simconnect_receiver: Receiver<SimConnectPacket>,
    socket_sender: Sender<SimConnectPacket>,
    sender: Sender<Event>,
    receiver: Receiver<Event>,
) -> Result<(), anyhow::Error> {
    SimConnect::new(simconnect_receiver, socket_sender, sender, receiver)
        .run()
        .await?;

    Ok(())
}
