use bevy::{
prelude::{Command, Commands, Component, Resource, World},
tasks::IoTaskPool,
};
pub use matchbox_socket;
use matchbox_socket::{MessageLoopFuture, WebRtcSocket, WebRtcSocketBuilder};
use std::{
fmt::Debug,
ops::{Deref, DerefMut},
};
#[derive(Resource, Component, Debug)]
#[allow(dead_code)] pub struct MatchboxSocket(WebRtcSocket, Box<dyn Debug + Send + Sync>);
impl Deref for MatchboxSocket {
type Target = WebRtcSocket;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for MatchboxSocket {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<WebRtcSocketBuilder> for MatchboxSocket {
fn from(builder: WebRtcSocketBuilder) -> Self {
Self::from(builder.build())
}
}
impl From<(WebRtcSocket, MessageLoopFuture)> for MatchboxSocket {
fn from((socket, message_loop_fut): (WebRtcSocket, MessageLoopFuture)) -> Self {
let task_pool = IoTaskPool::get();
let task = task_pool.spawn(message_loop_fut);
MatchboxSocket(socket, Box::new(task))
}
}
struct OpenSocket(WebRtcSocketBuilder);
impl Command for OpenSocket {
fn apply(self, world: &mut World) {
world.insert_resource(MatchboxSocket::from(self.0));
}
}
pub trait OpenSocketExt {
fn open_socket(&mut self, socket_builder: WebRtcSocketBuilder);
}
impl OpenSocketExt for Commands<'_, '_> {
fn open_socket(&mut self, socket_builder: WebRtcSocketBuilder) {
self.queue(OpenSocket(socket_builder))
}
}
struct CloseSocket;
impl Command for CloseSocket {
fn apply(self, world: &mut World) {
world.remove_resource::<MatchboxSocket>();
}
}
pub trait CloseSocketExt {
fn close_socket(&mut self);
}
impl CloseSocketExt for Commands<'_, '_> {
fn close_socket(&mut self) {
self.queue(CloseSocket)
}
}
impl MatchboxSocket {
pub fn new_unreliable(room_url: impl Into<String>) -> MatchboxSocket {
Self::from(WebRtcSocket::new_unreliable(room_url))
}
pub fn new_reliable(room_url: impl Into<String>) -> MatchboxSocket {
Self::from(WebRtcSocket::new_reliable(room_url))
}
}