use log::trace;

#[derive(Clone, Copy)]
pub struct SoundTimer {
    counter: i32
}

impl SoundTimer {
    pub fn current(&self) -> i32 {
        self.counter
    }
    pub fn new() -> Self {
        SoundTimer {
            counter: 0
        }
    }
    pub fn set_timer(&mut self, new_value: i32) {
        trace!("SETTING SOUND TIMER TO {new_value}");
        self.counter = new_value
    }

    pub fn tick(&mut self) {
        trace!("TICKING SOUND FROM {} to {}", self.counter, self.counter - 1);
        if self.counter > 0 {
            self.counter -= 1;
            /*
            todo: this breaks tests.  maybe its wrong?
            if let good_thread = thread::spawn(|| {
                beep(440).expect("Unable to beep");
                thread::sleep(time::Duration::from_millis(500));
            }).join().unwrap().
             */
        }
    }

    pub fn reset(&mut self) {
        self.counter = 0x00;
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn smoke() {
        assert!(true)
    }

    #[test]
    fn ticks_reduce_time() {
        let mut st = SoundTimer::new();
        st.set_timer(100);
        st.tick();
        st.tick();
        st.tick();
        assert_eq!(st.current(), 97);
    }

    #[test]
    fn out_of_ticks_works() {
        let mut st = SoundTimer::new();
        st.set_timer(0);
        st.tick();
        st.tick();
        st.tick();
        assert_eq!(st.current(), 0);
    }
}