// src/dma_timer.rs

use embassy_stm32::{
    peripherals::TIM6,
    rcc,
    timer::low_level::Timer,
    Peri,
};
use core::mem;
use embassy_stm32::timer::BasicInstance;
use embassy_stm32::pac::timer::vals::Urs;

/// Initializes TIM6 to tick at `baud * oversample` frequency.
/// Each TIM6 update event triggers one DMA beat.
pub fn init_tim6_for_uart<'d>(tim6: Peri<'d, TIM6>, baud: u32, oversample: u16) {
    rcc::enable_and_reset::<TIM6>();
    let ll = Timer::new(tim6);
    configure_basic_timer(&ll, baud, oversample);
    mem::forget(ll);
}

// Shared internal helper — identical CR1/ARR setup
fn configure_basic_timer<T: BasicInstance>(ll: &Timer<'_, T>, baud: u32, oversample: u16) {
    let f_timer = rcc::frequency::<T>().0;
    let target = baud.saturating_mul(oversample.max(1) as u32).max(1);

    // Compute ARR (prescaler = 0)
    let mut arr = (f_timer / target).saturating_sub(1) as u16;
    if arr == 0 { arr = 1; }

    ll.regs_basic().cr1().write(|w| {
        w.set_cen(false);
        w.set_opm(false);
        w.set_udis(false);
        w.set_urs(Urs::ANY_EVENT);
    });

    ll.regs_basic().psc().write_value(0u16);
    ll.regs_basic().arr().write(|w| w.set_arr(arr));
    ll.regs_basic().dier().modify(|w| w.set_ude(true));
    ll.regs_basic().egr().write(|w| w.set_ug(true));

    ll.regs_basic().cr1().write(|w| {
        w.set_opm(false);
        w.set_cen(true);
        w.set_udis(false);
        w.set_urs(Urs::ANY_EVENT);
    });
}
