import threading
from xml.etree.ElementTree import Element


class Dialog(object):
    def __init__(
        self,           # type: Dialog
        id,             # type: int
        xml,            # type: Element
        timeout,        # type: int
        asynch,         # type: bool
    ):
        self.id = id
        self.xml = xml
        self.timeout = timeout
        self.asynch = asynch
        self.response = None

        self._condition = threading.Condition()

    @classmethod
    def from_xml(
        cls,
        xml_element,        # type: Element
    ):
        if xml_element.tag != "PosDialog" or "id" not in xml_element.attrib:
            return None

        dialog_id = int(xml_element.attrib["id"])
        timeout = int(xml_element.attrib["timeout"])
        asynch_str = xml_element.attrib.get("asynch", "false").lower()
        asynch = asynch_str == "true"

        xml_content = None
        children = list(xml_element)
        if children:
            xml_content = children[0]

        return cls(
            id=dialog_id,
            xml=xml_content,
            timeout=timeout,
            asynch=asynch
        )

    def to_xml(self):
        # type: (...) -> Element

        dialog_el = Element(
            "PosDialog",
            attrib={
                "id": str(self.id),
                "timeout": str(self.timeout),
                "asynch": str(self.asynch).lower(),
            },
        )

        if self.xml is not None:
            dialog_el.append(self.xml)
        return dialog_el

    def wait_for_response(self):
        if self.asynch:
            return None

        with self._condition:
            wait_timeout = None if self.timeout == 0 else self.timeout / 1000.0
            if not self._condition.wait(wait_timeout):
                return None

            return self.response

    def set_response(self, response):
        with self._condition:
            self.response = response
            self._condition.notify_all()
