use alloc::collections::VecDeque;

use super::IPCError;

#[derive(Debug)]

pub struct ChannelPermission {
    pub owner: bool,
    pub producer: bool,

    pub consumer: bool,
    /// Whether or not the process can be destructive about reading
    pub distructive_consumer: bool,
}

#[derive(Debug)]
pub struct Channel {
    pub public: bool,
    _name: String,
    inner: VecDeque<ChannelMessage>,
}

impl Channel {
    pub fn new<S: Into<String>>(name: S, public: bool) -> Self {
        let deq = VecDeque::from([]);

        Self {
            public,
            _name: name.into(),
            inner: deq,
        }
    }

    pub fn read(&mut self) -> Result<ChannelMessage, IPCError> {
        if let Some(msg) = self.inner.pop_front() {
            return Ok(msg);
        }
        return Err(IPCError::EmptyChannel);
    }

    pub fn write(&mut self, data: ChannelMessage) -> Result<(), IPCError> {
        self.inner.push_back(data);

        Ok(())
    }
}

pub enum ChannelError {
    EmptyBuffer,
    InvalidPermissions,
}

#[derive(Debug)]
pub struct ChannelMessage {
    inner: [u8; 4096],
}

impl ChannelMessage {
    pub fn new<S: Into<String>>(data: S) -> Result<Self, IPCError> {
        let data = data.into();
        let mut message = Self { inner: [0; 4096] };

        if data.len() > 4096 {
            return Err(IPCError::InvalidMessage);
        } else {
            let mut idx = 0;
            for b in data.bytes() {
                message.inner[idx] = b;
                idx += 1;
            }
        }

        Ok(message)
    }
}
