use crate::inspect::smp::common::*;
use crate::inspect::smp::*;

pub(in crate::inspect::smp) fn find_first_ascii_run(bytes: &[u8]) -> Option<SmpAsciiPreview> {
    let mut start = None;

    for (index, byte) in bytes.iter().copied().enumerate() {
        if is_ascii_preview_byte(byte) {
            start.get_or_insert(index);
            continue;
        }

        if let Some(run_start) = start.take() {
            if index - run_start >= MIN_ASCII_RUN_LEN {
                return Some(build_ascii_preview(bytes, run_start, index));
            }
        }
    }

    start.and_then(|run_start| {
        if bytes.len() - run_start >= MIN_ASCII_RUN_LEN {
            Some(build_ascii_preview(bytes, run_start, bytes.len()))
        } else {
            None
        }
    })
}

pub(in crate::inspect::smp) fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

pub(in crate::inspect::smp) fn ascii_preview(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|byte| match byte {
            0x20..=0x7e => char::from(*byte),
            _ => '.',
        })
        .collect()
}

pub(in crate::inspect::smp) fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    format!("{digest:x}")
}
