use crate::{LooperError, Result};
use tokio::net::{UnixListener, UnixStream};

pub(crate) type PlatformStream = UnixStream;

pub(crate) struct PlatformListener {
    listener: UnixListener,
}

impl PlatformListener {
    pub async fn accept(&mut self) -> Result<PlatformStream> {
        let (stream, _) = self
            .listener
            .accept()
            .await
            .map_err(|_| LooperError::JackConnection(std::panic::Location::caller()))?;
        Ok(stream)
    }
}

pub(crate) async fn create_listener(socket_path: &str) -> Result<PlatformListener> {
    // Remove existing socket file if it exists
    let _ = std::fs::remove_file(socket_path);

    let listener = UnixListener::bind(socket_path)
        .map_err(|_| LooperError::JackConnection(std::panic::Location::caller()))?;

    Ok(PlatformListener { listener })
}
