use std::collections::VecDeque;
use std::sync::Mutex;
use std::time::Duration;

use sgclaw::pipe::{AgentMessage, BrowserMessage, PipeError, Transport};

pub struct MockTransport {
    incoming: Mutex<VecDeque<BrowserMessage>>,
    sent: Mutex<Vec<AgentMessage>>,
}

impl MockTransport {
    pub fn new(messages: Vec<BrowserMessage>) -> Self {
        Self {
            incoming: Mutex::new(VecDeque::from(messages)),
            sent: Mutex::new(Vec::new()),
        }
    }

    #[allow(dead_code)]
    pub fn sent_messages(&self) -> Vec<AgentMessage> {
        self.sent.lock().unwrap().clone()
    }
}

impl Transport for MockTransport {
    fn send(&self, message: &AgentMessage) -> Result<(), PipeError> {
        self.sent.lock().unwrap().push(message.clone());
        Ok(())
    }

    fn recv_timeout(&self, _timeout: Duration) -> Result<BrowserMessage, PipeError> {
        self.incoming
            .lock()
            .unwrap()
            .pop_front()
            .ok_or(PipeError::Timeout)
    }
}
