"""Builder for ``<ChildObjects>`` elements in HOL DMSQuery XML."""
import xml.etree.ElementTree as ET
from typing import Optional

from ecmind_blue_client.ecm.builder._common import (
    DmsQueryFieldSchemaT,
    DmsQueryObjectSchemaT,
)
from ecmind_blue_client.ecm.builder._dms_query_object_type_hol import (
    DmsQueryChildObjectType,
    DmsQuerySubObjectType,
)


class DmsQueryChildObjects:
    """Represents the ``<ChildObjects>`` element in the DMSQuery XML structure.

    Configures which child object types are included in HOL query results and how deep
    the hierarchy is exported.
    """

    def __init__(
        self,
        parent: ET.Element,
        child_schema: DmsQueryObjectSchemaT,
        export_depth: int,
        field_schema: Optional[DmsQueryFieldSchemaT] = None,
    ):
        """
        Args:
            parent (ET.Element): The parent XML element.
            child_schema (DmsQueryObjectSchemaT): Object schema for child objects
                (``DEF``, ``ALL``, ``REGISTER``, ``DOCUMENTS``).
            export_depth (int): Hierarchy depth to export. 0 means current level only.
            field_schema (Optional[DmsQueryFieldSchemaT]): Field schema applied to all
                child object types. If ``None``, no ``field_schema`` attribute is written.
        """
        self._node = ET.SubElement(parent, "ChildObjects", {"child_schema": child_schema, "export_depth": str(export_depth)})

        if field_schema is not None:
            self._node.attrib["field_schema"] = field_schema

        self._parent_node = parent

    def __enter__(self):
        return self

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

    def child_object_type(self, internal_name_or_type_id: str | int) -> DmsQueryChildObjectType:
        """
        Return a new DmsQueryObjectType instance for the given internal name or type id

        Args:
            internal_name_or_type_id (str | int): The internal name or type id of the object type

        Returns:
            DmsQueryObjectType: A new DmsQueryObjectType instance for the given internal name or type id representing the <ObjectType>
                element in the DMSQuery XML structure
        """
        return DmsQueryChildObjectType(self._node, internal_name_or_type_id)

    def sub_object_type(self, internal_name_or_type_id: str | int) -> DmsQuerySubObjectType:
        """Adds a ``<SubObjectType>`` element as an alternative to ``<ChildObjectType>``.

        Args:
            internal_name_or_type_id (str | int): The internal name or type ID of the sub-object type.

        Returns:
            DmsQuerySubObjectType: The sub-object type builder.
        """
        return DmsQuerySubObjectType(self._node, internal_name_or_type_id)
