use fugit::TimerInstantU32;
use core::convert::Infallible;
use embedded_nal::nb;

// use std::{
//     convert::Infallible,
//     time::{SystemTime, UNIX_EPOCH},
// };
pub struct SysClock {
    start_time: u32,
    countdown_end: Option<u32>,
}

impl SysClock {
    pub fn new() -> Self {
        Self {
            start_time: Self::epoch(),
            countdown_end: None,
        }
    }

    // pub fn epoch() -> u32 {
    //     SystemTime::now()
    //         .duration_since(UNIX_EPOCH)
    //         .expect("Time went backwards")
    //         .as_millis() as u32
    // }
    pub fn epoch() -> u32 {
        embassy_time::Instant::now().as_ticks() as u32
    }


    pub fn now(&self) -> u32 {
        Self::epoch() - self.start_time
    }
}

impl fugit_timer::Timer<1000> for SysClock {
    type Error = Infallible;

    fn now(&mut self) -> fugit::TimerInstantU32<1000> {
        TimerInstantU32::from_ticks(SysClock::now(self))
    }

    fn start(&mut self, duration: fugit::TimerDurationU32<1000>) -> Result<(), Self::Error> {
        todo!()
    }

    fn cancel(&mut self) -> Result<(), Self::Error> {
        todo!()
    }

    fn wait(&mut self) -> nb::Result<(), Self::Error> {
        todo!()
    }
}


// #[derive(Copy, Clone, Debug)]
// pub struct StandardClock {
//     //start: std::time::Instant,
//     start: embassy_time::Instant,
// }

// impl Default for StandardClock {
//     fn default() -> Self {
//         Self {
//             start: embassy_time::Instant::now(),
//         }
//     }
// }

// impl embedded_time::Clock for StandardClock {
//     /// With a 64-bit tick register, the clock can represent times up to approximately 594 years in
//     /// duration, after which the clock will roll over.
//     type T = u64;

//     /// Each tick of the clock is equivalent to 1 nanosecond.
//     const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000_000_000);

//     /// Get the current time from the clock.
//     fn try_now(&self) -> Result<Instant<Self>, embedded_time::clock::Error> {
//         let now = embassy_time::Instant::now();

//         let elapsed = now.duration_since(self.start);

//         // Note: We are discarding the upper 64 bits of nanoseconds. However, even while doing so,
//         // we can represent ~594 years of time, so this should not be relevant.
//         Ok(Instant::new(elapsed.as_micros() as u64))
//     }
// }

