from __future__ import annotations

from typing import Iterable

from openpyxl.styles import Alignment, Border, Font, PatternFill
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.worksheet import Worksheet

from .canvas import Box


def column_letter(col_index: int) -> str:
    return get_column_letter(col_index)



def set_col_widths(ws: Worksheet, start_col: int, widths: list[float]) -> None:
    for offset, width in enumerate(widths):
        ws.column_dimensions[column_letter(start_col + offset)].width = width



def iter_box_cells(ws: Worksheet, box: Box) -> Iterable:
    for row in range(box.r1, box.r2 + 1):
        for col in range(box.c1, box.c2 + 1):
            yield ws.cell(row=row, column=col)



def apply_range_style(
    ws: Worksheet,
    box: Box,
    font: Font | None = None,
    fill: PatternFill | None = None,
    border: Border | None = None,
    alignment: Alignment | None = None,
    number_format: str | None = None,
) -> None:
    for cell in iter_box_cells(ws, box):
        if font is not None:
            cell.font = font
        if fill is not None:
            cell.fill = fill
        if border is not None:
            cell.border = border
        if alignment is not None:
            cell.alignment = alignment
        if number_format is not None:
            cell.number_format = number_format
