"""Field set widget for label+value display."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.containers import Horizontal
from textual.widget import Widget
from textual.widgets import Label


def to_class_case(snake_str: str) -> str:
    """Convert a snake_case string to ClassCase.

    Spaces are converted to underscores before conversion.

    Args:
        snake_str: The snake_case string.

    Returns:
        The ClassCase string.
    """
    components = snake_str.replace(" ", "_").split("_")
    return "".join(x.title() for x in components[0:])


class FieldSet(Horizontal):
    """Field set consisting of Label and value widget(s)."""

    DEFAULT_CSS = """
    FieldSet {
        height: auto;
        width: 100%;
    }
    FieldSet .field-label {
        width: 15;
        text-style: bold;
    }
    """
    label: Label

    def __init__(
        self,
        label: str,
        *fields: Widget,
    ) -> None:
        """Initialize the field set.

        Args:
            label: The label text
            fields: Value widgets to display after the label
        """
        base_name = to_class_case(label.replace("/", ""))
        super().__init__(
            id=f"{base_name}FieldSet",
            name=f"{base_name}FieldSet",
        )
        self.label = Label(label, id=f"{base_name}Label", classes="field-label")
        self.fields = fields

    def compose(self) -> ComposeResult:
        yield self.label
        yield from self.fields
