use std::{
    io,
    os::{
        fd::{AsRawFd, RawFd},
        yggdrasil::io::message_channel::{MessageChannel, MessageReceiver},
    },
};

use yggdrasil_rt::debug::DebugFrame;

pub struct Comm {
    channel: MessageChannel,
    buffer: [u8; 1024],
}

impl Comm {
    pub fn open(name: &str) -> Result<Self, io::Error> {
        let channel = MessageChannel::open(name, true)?;
        Ok(Self {
            channel,
            buffer: [0; 1024],
        })
    }

    pub fn recv(&mut self) -> Result<DebugFrame, io::Error> {
        let (_, len) = self.channel.receive_message(&mut self.buffer)?;
        let message = serde_json::from_slice(&self.buffer[..len]).unwrap();
        Ok(message)
    }
}

impl AsRawFd for Comm {
    fn as_raw_fd(&self) -> RawFd {
        self.channel.as_raw_fd()
    }
}
