use std::{
    cell::RefCell,
    io::{self, Write},
    rc::Rc,
};

use crate::logger::{Logger, Verbosity};

#[derive(Clone, Debug, Default)]
pub(crate) struct SharedLog {
    bytes: Rc<RefCell<Vec<u8>>>,
}

impl SharedLog {
    pub(crate) fn contents(&self) -> String {
        String::from_utf8(self.bytes.borrow().clone()).unwrap()
    }
}

impl Write for SharedLog {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.bytes.borrow_mut().extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

pub(crate) fn quiet_logger() -> Logger<Vec<u8>> {
    Logger::with_writer(Verbosity::Quiet, Vec::new())
}

pub(crate) fn logger_with_shared_log(verbosity: Verbosity) -> (Logger<SharedLog>, SharedLog) {
    let shared_log = SharedLog::default();
    let logger = Logger::with_writer(verbosity, shared_log.clone());

    (logger, shared_log)
}
