use log::trace;
use rpi_pal::pwm::Pwm;
use std::time::Duration;
use crate::hardware::pwm::PwmOutput;
use anyhow::Result;

const PWM_PERIOD: Duration = Duration::from_micros(1000); // 1kHz

#[derive(Debug)]
pub struct PwmWrapper {
    pwm: Pwm,
}

impl PwmWrapper {
    pub fn new(mut pwm: Pwm) -> Result<Self> {
        trace!("PwmWrapper::new(pwm: {pwm:?})");
        pwm.set_period(PWM_PERIOD)?;
        pwm.set_duty_cycle(0.0)?;
        pwm.enable()?;
        pwm.set_reset_on_drop(true);
        Ok(Self { pwm })
    }
}

impl PwmOutput for PwmWrapper {

    fn set_duty_cycle(&mut self, duty_cycle: f64) -> Result<()> {
        trace!("PwmWrapper::set_duty_cycle(self: {self:?}, duty_cycle: {duty_cycle})");
        Ok(self.pwm.set_duty_cycle(duty_cycle)?)
    }
}
