use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use tokio::net::TcpStream;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::MaybeTlsStream;
use crate::WispPktType;
use crate::types::{WispContext, ConnectionType};
pub async fn WispSetServer(ws_ctx: &mut WispContext, wispURL: &str) {
ws_ctx.server_url = wispURL.to_string();
let (mut ws_stream, _) = connect_async(wispURL).await.unwrap();
if let Some(msg) = ws_stream.next().await {
match msg {
Ok(Message::Binary(data)) => {
if data.len() >= 5 && data[0] == WispPktType::CONTINUE as u8 {
let stream_id = u32::from_le_bytes([data[1], data[2], data[3], data[4]]);
if stream_id != 0 {
panic!("Expected CONTINUE with stream_id 0, got {}", stream_id);
}
}
}
other => {
panic!("Unexpected initial message: {:?}", other);
}
}
} else {
panic!("No initial CONTINUE packet received from Wisp server.");
}
ws_ctx.connection = Some(ws_stream);
}
pub fn WispGetServer(ws_ctx: &WispContext) -> String {
ws_ctx.server_url.clone()
}
pub fn WispSetConnectionType(ws_ctx: &mut WispContext, conn: ConnectionType) {
ws_ctx.conn_type = conn;
}
pub fn WispGetConnectionType(ws_ctx: &WispContext) -> ConnectionType {
ws_ctx.conn_type
}
pub async fn WispSwitchServer(ws_ctx: &mut WispContext, newWispURL: &str) {
WispClose(ws_ctx).await;
WispSetServer(ws_ctx, newWispURL).await;
}
pub async fn WispClose(ws_ctx: &mut WispContext) {
if let Some(mut stream) = ws_ctx.connection.take() {
let _ = stream.close(None).await;
}
}