//! WebSocket receiver implementation for web-sys backend.

use crate::{Message, Result};
use crate::traits::WebSocketReceiverTrait;
use wasm_bindgen::closure::Closure;
use web_sys::{MessageEvent, CloseEvent};
use std::future::Future;

/// WebSocket receiver.
#[derive(Debug)]
pub struct WebSocketReceiver {
    pub(crate) receiver: async_channel::Receiver<Result<Message>>,
    pub(crate) _on_message_callback: Closure<dyn FnMut(MessageEvent)>,
    pub(crate) _on_close_callback: Closure<dyn FnMut(CloseEvent)>
}

impl WebSocketReceiverTrait for WebSocketReceiver {
    fn next(&mut self) -> impl Future<Output = Result<Option<Message>>> {
        async move {
            match self.receiver.recv().await {
                Ok(Ok(msg)) => Ok(Some(msg)),
                Ok(Err(e)) => Err(e),
                Err(_) => Ok(None), // Channel closed, stream ended
            }
        }
    }
}

