from typing import Optional

from xml.etree.ElementTree import Element

from pymasep.common.base_object import BaseObject


class Intention(BaseObject):

    def __init__(self, environment,
                 name: Optional[str] = None,
                 xml_node: Optional[Element] = None,
                 template=None,
                 parent=None):
        """
        Constructor of the Intention
        :param environment the environment
        :param name name of the BaseObject
        :param xml_node xml used to create the object.
        :param template template of the base object. Needed if no xml_node.
                        CreationException is raised if no xml or no template is present
        :param parent
        """
        super().__init__(environment=environment, name=name, template=template, xml_node=xml_node, parent=parent)
        self.name: str = 'intention'
        self.intentions = []
        self.state: str = 'run'

    def add_intention(self, intention) -> None:
        self.intentions.append(intention)

    def id_str(self) -> str:
        id_str_actions = ''
        for a in self.intentions:
            id_str_actions += a.id_str()
        return super().id_str() + id_str_actions

    def to_xml(self) -> Element:
        """
        Transform the Intention to xml
        :return xml version of the ObjectState
        """
        result = super().to_xml()
        for one_intention in self.intentions:
            intention_element = one_intention.to_xml()
            result.append(intention_element)
        return result

    def from_xml(self, environment, xml_node: Element) -> None:
        super().from_xml(environment=environment, xml_node=xml_node)
        for action_xml in xml_node:
            action = self.environment.create_action(xml_node=action_xml)
            self.add_intention(action)
