"""Represents a ``<TableField>`` element embedded within a LOL ``<Row>``."""

import xml.etree.ElementTree as ET


class DmsContentLolRowTableField:
    """An embedded table field within a LOL ``<Row>`` element.

    In LOL responses, a ``<Row>`` may contain ``<TableField>`` children that represent
    nested table dialog data. The column names for these fields are declared at the
    ``<Rowset>/<Columns>/<TableField>`` level and must be passed in at construction time.

    Attributes:
        node: The ``<TableField>`` XML element from the ``<Row>``.
        columns: Ordered list of column names from ``Rowset/Columns/TableField/Columns/Column``.
    """

    def __init__(self, node: ET.Element, columns: list[str]):
        self._node = node
        self._columns = columns

    @property
    def internal_name(self) -> str:
        """Internal name of this table field."""
        return self._node.get("internal_name", "")

    @property
    def name(self) -> str:
        """Display name of this table field."""
        return self._node.get("name", "")

    @property
    def dbname(self) -> str:
        """Database column name of this table field."""
        return self._node.get("dbname", "")

    @property
    def columns(self) -> list[str]:
        """Ordered column names as declared in ``Rowset/Columns/TableField/Columns/Column``."""
        return self._columns

    @property
    def rows(self) -> list[dict[str, str]]:
        """Returns all rows as a list of ``{column_name: raw_value}`` dicts.

        Values are mapped positionally to the column names supplied at construction time.
        Columns without a corresponding value default to an empty string.

        Returns:
            list[dict[str, str]]: One dict per ``<Row>`` element, keyed by column name.
        """
        result: list[dict[str, str]] = []
        for row_node in self._node.findall("Row"):
            values = [v.text or "" for v in row_node.findall("Value")]
            result.append({col: values[i] if i < len(values) else "" for i, col in enumerate(self._columns)})
        return result
