use web_sys::MessageEvent;
use wasm_bindgen::JsCast;
use crate::Message;
use std::convert::TryFrom;

impl TryFrom<MessageEvent> for Message {
    type Error = crate::error::Error;

    fn try_from(event: MessageEvent) -> std::result::Result<Self, Self::Error> {
        if let Ok(text) = event.data().dyn_into::<js_sys::JsString>() {
            Ok(Message::Text(text.as_string().unwrap_or_default()))
        } else if let Ok(binary) = event.data().dyn_into::<js_sys::ArrayBuffer>() {
            Ok(Message::Binary(js_sys::Uint8Array::new(&binary).to_vec()))
        } else {
            Err(crate::error::Error::UnsupportedMessageType(
                "Unsupported message type in MessageEvent".to_string()
            ))
        }
    }
}
