from datetime import datetime

from PIL import ImageDraw

from .common import (
    CHART_HOURS,
    ChartBounds,
    FontType,
    RenderMetrics,
    build_hour_slots,
    measure_text,
)

TEMPERATURE_LABEL_SAMPLE = "00"


def compute_x_axis_y(
    draw: ImageDraw.ImageDraw,
    font: FontType,
    chart_top: int,
    chart_bottom: int,
    plot_padding: int,
) -> int | None:
    _, label_height, _ = measure_text(draw, font, TEMPERATURE_LABEL_SAMPLE)
    x_axis_y = round(chart_bottom - label_height - (3 * plot_padding))
    if x_axis_y <= chart_top + (2 * plot_padding):
        return None
    return x_axis_y


def build_chart_context(
    draw: ImageDraw.ImageDraw,
    font: FontType,
    chart_bounds: ChartBounds,
    now: datetime,
    metrics: RenderMetrics,
) -> tuple[list[datetime], int] | None:
    if (
        chart_bounds.right <= chart_bounds.left + metrics.min_chart_dimension
        or chart_bounds.bottom <= chart_bounds.top + metrics.min_chart_dimension
    ):
        return None

    x_axis_y = compute_x_axis_y(
        draw=draw,
        font=font,
        chart_top=chart_bounds.top,
        chart_bottom=chart_bounds.bottom,
        plot_padding=metrics.plot_padding,
    )
    if x_axis_y is None:
        return None

    return build_hour_slots(now, CHART_HOURS), x_axis_y
