use std::fmt;

use crate::write_utils::pad;

/// Write a comma-separated list of items using `fmt_indented`.
///
/// If the total subelements count is <= `threshold`, items are written inline
/// separated by `, `. Otherwise, each item starts on a new line at `indentation`.
///
/// The `fmt_item` closure receives `(formatter, item, indentation)` and should
/// call the item's `fmt_indented` method.
pub fn write_comma_list<T>(
    f: &mut fmt::Formatter<'_>,
    items: &[T],
    indentation: usize,
    total_subelements: usize,
    threshold: usize,
    fmt_item: impl Fn(&mut fmt::Formatter<'_>, &T, usize) -> fmt::Result,
) -> fmt::Result {
    let flat = total_subelements <= threshold;
    for (i, item) in items.iter().enumerate() {
        if i > 0 {
            if flat {
                write!(f, ", ")?;
            } else {
                writeln!(f, ",")?;
                pad(f, indentation)?;
            }
        }
        fmt_item(f, item, indentation)?;
    }
    Ok(())
}
