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

from ecmind_blue_client.ecm.builder._common import (
    DmsQueryFieldSchemaT,
    DmsQueryFieldValueT,
    DmsQueryObjectSchemaT,
)
from ecmind_blue_client.ecm.builder._dms_query_fulltext import DmsQueryFulltext


class DmsQueryFullextQuery:
    """Represents the ``<FulltextQuery>`` element within an ``<Archive>`` in the DMSQuery XML.

    Performs a full-text search across the archive. Optionally includes child objects in the
    result via ``child_objects()``. The ``fulltext`` property gives access to the underlying
    ``<Fulltext>`` element for setting RetrievalWare search-engine attributes.
    """

    def __init__(self, parent: ET.Element, value: DmsQueryFieldValueT):
        """
        Args:
            parent (ET.Element): The parent ``<Archive>`` element.
            value (DmsQueryFieldValueT): The full-text search term.
        """
        self._node = ET.SubElement(parent, "FulltextQuery")
        self._parent_node = parent
        self._fulltext = DmsQueryFulltext(self._node, value)

    def __enter__(self):
        return self

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

    @property
    def fulltext(self) -> DmsQueryFulltext:
        """The ``<Fulltext>`` element; use to configure RetrievalWare search-engine attributes."""
        return self._fulltext

    def child_objects(
        self, child_schema: DmsQueryObjectSchemaT = "DEF", export_depth: int = 0, field_schema: Optional[DmsQueryFieldSchemaT] = None
    ):
        """Adds a ``<ChildObjects>`` element before the ``<Fulltext>`` element as required by the XSD.

        Args:
            child_schema (DmsQueryObjectSchemaT): Object schema for child objects. Defaults to ``"DEF"``.
            export_depth (int): Hierarchy depth to export. 0 means current level only. Defaults to 0.
            field_schema (Optional[DmsQueryFieldSchemaT]): Field schema for child types. Defaults to ``None``.

        Returns:
            DmsQueryChildObjects: The child objects builder.
        """
        from ecmind_blue_client.ecm.builder._dms_query_child_objects import (
            DmsQueryChildObjects,
        )

        result = DmsQueryChildObjects(self._node, child_schema, export_depth, field_schema)
        # XSD requires <ChildObjects> before <Fulltext>; move <Fulltext> to end.
        self._node.remove(self._fulltext._node)  # pylint: disable=protected-access
        self._node.append(self._fulltext._node)  # pylint: disable=protected-access
        return result
