use termios::*;

use crate::panic;

/// can toggle raw mode on a fd, at the latest disables it when it gets dropped
pub struct ScopedRawMode {
    fd: i32,
    settings: Termios,
}

impl Drop for ScopedRawMode {
    fn drop(&mut self) {
        self.disable();
    }
}

impl ScopedRawMode {
    pub fn on_fd(fd: i32) -> Self {
        let settings = Termios::from_fd(fd).unwrap();
        Self { fd, settings }
    }

    pub fn enable(&self) {
        let mut settings = self.settings;
        cfmakeraw(&mut settings);
        tcsetattr(self.fd, TCSANOW, &settings).unwrap();
        panic::enable_cr();
    }

    pub fn disable(&self) {
        tcsetattr(self.fd, TCSANOW, &self.settings).unwrap();
        panic::disable_cr();
    }
}
