// src/uart_emulation.rs

use heapless::Vec;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Parity {
    None,
    Even,
    Odd,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StopBits {
    One,
    Two,
}

#[derive(Clone, Copy, Debug)]
pub struct UartConfig {
    pub data_bits: u8,
    pub parity: Parity,
    pub stop_bits: StopBits,
}

impl Default for UartConfig {
    fn default() -> Self {
        Self {
            data_bits: 8,
            parity: Parity::None,
            stop_bits: StopBits::One,
        }
    }
}

/// Encodes one byte into a sequence of GPIO BSRR words
pub fn encode_uart_byte_cfg(
    pin_bit: u8,
    data: u8,
    cfg: &UartConfig,
    out: &mut [u32; 12],
) -> usize {
    // GPIOx_BSRR register str. 636 kap. 13.4.7
    let set_high = |bit: u8| -> u32 { 1u32 << bit };
    // let set_low = |bit: u8| -> u32 { 0 }; // ODR
    let set_low = |bit: u8| -> u32 { 1u32 << (bit as u32 + 16) }; // BSRR

    let nbits = cfg.data_bits;
    let mut idx = 0usize;

    // START bit (LOW)
    out[idx] = set_low(pin_bit);
    idx += 1;

    // Data bits, LSB-first
    for i in 0..nbits {
        let one = ((data >> i) & 1) != 0;
        out[idx] = if one { set_high(pin_bit) } else { set_low(pin_bit) };
        idx += 1;
    }

    // Parity
    match cfg.parity {
        Parity::None => {}
        Parity::Even | Parity::Odd => {
            let mask: u8 = if nbits == 8 { 0xFF } else { (1u16 << nbits) as u8 - 1 };
            let ones = (data & mask).count_ones() & 1;
            let par_bit_is_one = match cfg.parity {
                Parity::Even => ones == 1,
                Parity::Odd => ones == 0,
                _ => false,
            };
            out[idx] = if par_bit_is_one {
                set_high(pin_bit)
            } else {
                set_low(pin_bit)
            };
            idx += 1;
        }
    }

    // STOP bits (HIGH)
    let stop_ticks = match cfg.stop_bits {
        StopBits::One => 1,
        StopBits::Two => 2,
    };
    for _ in 0..stop_ticks {
        out[idx] = set_high(pin_bit);
        idx += 1;
    }

    idx
}

/// Decode an oversampled stream of logic levels into UART bytes.
/// Returns (decoded bytes, number of samples consumed/processed).
pub fn decode_uart_samples(
    samples: &[u8],
    oversample: u16,
    cfg: &UartConfig,
) -> (heapless::Vec<u8, 256>, usize) {
    let mut out = Vec::<u8, 256>::new();
    let mut idx = 0usize;
    let nbits = cfg.data_bits as usize;
    let ovs = oversample as usize;

    // Calculate total frame width in samples to ensure we have enough data
    // 1 start + n data + parity? + stops
    let parity_bits = match cfg.parity {
        Parity::None => 0,
        _ => 1,
    };
    let stop_bits_count = match cfg.stop_bits {
        StopBits::One => 1,
        StopBits::Two => 2,
    };
    let frame_bits = 1 + nbits + parity_bits + stop_bits_count;
    let frame_len = frame_bits * ovs;

    // Get sample in the middle of the bit
    let get_bit = |i: usize| -> u8 {
        if samples[i] != 0 { 1 } else { 0 }
    };

    // Decode while remaining samples for a full frame
    while idx + frame_len <= samples.len() {
        // Start - idle HIGH to start LOW
        if samples[idx] != 0 && samples[idx + 1] == 0 {
            let center_offset = ovs / 2;
            let mut scan_idx = idx + center_offset;

            // Validate Start Bit
            if get_bit(scan_idx) != 0 {
                idx += 1; // False start (noise), move on
                continue;
            }

            // Move to center of first data bit
            scan_idx += ovs;

            // Read Data Bits
            let mut data: u8 = 0;
            for bit in 0..nbits {
                if get_bit(scan_idx) == 1 {
                    data |= 1 << bit;
                }
                scan_idx += ovs;
            }

            let mut error_data = false;
            if cfg.parity != Parity::None {
                let expected_parity = calculate_parity(data, cfg.parity);
                let actual_parity = get_bit(scan_idx);
                if expected_parity != actual_parity {
                    // Parity error
                    error_data = true;
                }
                scan_idx += ovs;
            }

            for _ in 0..stop_bits_count {
                if get_bit(scan_idx) == 0 {
                    // Framing error
                    error_data = true;
                    break;
                }
                scan_idx += ovs;
            }
            if error_data {
                idx += 1;
                continue;  // Skip this frame completely
            }

            let _ = out.push(data);
            idx = scan_idx;

            // Next startbit reach
            while idx < samples.len() && samples[idx] != 0 {
                idx += 1;
            }

            // Mensi hack
            if idx > 0 {
                idx -= 1;
            }
        } else {
            // No start bit detected here, move to next sample
            idx += 1;
        }
    }

    (out, idx)
}

/// Calculate the expected parity bit (0 or 1) for the given data and parity mode
fn calculate_parity(data: u8, parity: Parity) -> u8 {
    match parity {
        Parity::None => 0,
        Parity::Even | Parity::Odd => {
            let ones = data.count_ones() & 1;
            match parity {
                Parity::Even => ones as u8,  // If ones=1 (odd), emit 1 to make even
                Parity::Odd => (ones ^ 1) as u8,  // XOR - If ones=1 (odd), emit 0 to keep odd
                _ => 0,
            }
        }
    }
}
