use termichart_core::{Rect, Style};

use crate::cell::CellGrid;

/// Writes a string of text horizontally into the grid starting at `(col, row)`.
///
/// Characters that would fall outside the grid bounds are silently dropped.
pub fn draw_text(grid: &mut CellGrid, col: u16, row: u16, text: &str, style: Style) {
    for (i, ch) in text.chars().enumerate() {
        let c = col as usize + i;
        if c > u16::MAX as usize {
            break;
        }
        grid.set(c as u16, row, ch, style);
    }
}

/// Draws a horizontal line of a given character from `start_col` to `end_col`
/// (inclusive) at the specified `row`.
pub fn draw_hline(
    grid: &mut CellGrid,
    row: u16,
    start_col: u16,
    end_col: u16,
    ch: char,
    style: Style,
) {
    let lo = start_col.min(end_col);
    let hi = start_col.max(end_col);
    for col in lo..=hi {
        grid.set(col, row, ch, style);
    }
}

/// Draws a vertical line of a given character from `start_row` to `end_row`
/// (inclusive) at the specified `col`.
pub fn draw_vline(
    grid: &mut CellGrid,
    col: u16,
    start_row: u16,
    end_row: u16,
    ch: char,
    style: Style,
) {
    let lo = start_row.min(end_row);
    let hi = start_row.max(end_row);
    for row in lo..=hi {
        grid.set(col, row, ch, style);
    }
}

/// Fills an entire rectangle with the given character and style.
pub fn fill_rect(grid: &mut CellGrid, rect: &Rect, ch: char, style: Style) {
    for row in rect.y..rect.bottom() {
        for col in rect.x..rect.right() {
            grid.set(col, row, ch, style);
        }
    }
}
