"""Builder for ``<TableCondition>`` elements within a ``<ConditionObject>``."""
import xml.etree.ElementTree as ET

from ecmind_blue_client.ecm.builder._common import (
    DmsQueryConditionFieldOperatorsT,
    DmsQueryFieldValueT,
    write_field_value,
)


class DmsQueryTableCondition:
    """Represents a ``<TableCondition>`` element for filtering on table dialog field types.

    Add individual column conditions via ``table_column()``.
    """

    def __init__(self, parent: ET.Element, internal_name: str, row: int) -> None:
        """
        Args:
            parent (ET.Element): The parent XML element (e.g. ``<ConditionObject>``).
            internal_name (str): The internal name of the table field.
            row (int): The row index to filter on. 0 means no specific row restriction.
        """
        self._parent = parent
        self._node = ET.SubElement(self._parent, "TableCondition", {"internal_name": internal_name})
        if row != 0:
            self._node.attrib["row"] = str(row)

    def table_column(self, internal_name: str, value: DmsQueryFieldValueT, operator: DmsQueryConditionFieldOperatorsT = "="):
        """
        Adds a field condition to the current object type or condition object.

        Args:
            internal_name (str): The internal name of the field to condition on.
            value (ConditionFieldValueT): The value to compare the field against.
            operator (ConditionFieldOperatorsT, optional): The operator to use for the condition. Defaults to "=".
        """

        table_column_node = ET.SubElement(self._node, "TableColumn", {"internal_name": internal_name, "operator": operator})
        write_field_value(table_column_node, value)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        pass
