use embedded_hal::pwm::{ErrorKind, ErrorType, SetDutyCycle};
use log::trace;
use std::fmt::{Display, Formatter};

#[derive(Debug)]
pub struct SimPwm {
    duty_cycle: u16,
}

impl SimPwm {
    pub fn new() -> Self {
        trace!("SimPwm::new()");
        Self { duty_cycle: 0 }
    }
}

#[derive(Debug)]
pub struct ErrorWrapper(anyhow::Error);

impl embedded_hal::pwm::Error for ErrorWrapper {
    fn kind(&self) -> ErrorKind {
        ErrorKind::Other
    }
}

impl Display for ErrorWrapper {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::error::Error for ErrorWrapper {}

impl ErrorType for SimPwm {
    type Error = ErrorWrapper;
}

impl SetDutyCycle for SimPwm {
    fn max_duty_cycle(&self) -> u16 {
        trace!("SimPwm::max_duty_cycle()");
        u16::MAX
    }

    fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> {
        trace!("SimPwm::set_duty_cycle(duty: {duty})");
        self.duty_cycle = duty;
        Ok(())
    }
}
