//! Local connection
//!
//! Add types for adding local connections
use crate::{connection::ConnectionId, Error};
use nostr_rs_types::{Request, Response};
use tokio::sync::mpsc::{Receiver, Sender};

/// Local connection
pub struct LocalConnection {
    sender: Sender<(ConnectionId, Request)>,
    receiver: Receiver<Response>,
    conn_id: ConnectionId,
}

impl LocalConnection {
    /// Receive a message from the relayer
    pub async fn recv(&mut self) -> Option<Response> {
        self.receiver.recv().await
    }

    /// Sends a request to the relayer
    pub async fn send(&self, request: Request) -> Result<(), Error> {
        self.sender
            .send((self.conn_id, request))
            .await
            .map_err(|e| Error::LocalSendError(Box::new(e)))
    }
}

impl
    From<(
        ConnectionId,
        Receiver<Response>,
        Sender<(ConnectionId, Request)>,
    )> for LocalConnection
{
    fn from(
        value: (
            ConnectionId,
            Receiver<Response>,
            Sender<(ConnectionId, Request)>,
        ),
    ) -> Self {
        LocalConnection {
            conn_id: value.0,
            receiver: value.1,
            sender: value.2,
        }
    }
}
