from typing import Iterable, List

from maps_adv.export.lib.core.xml import XmlDoc, XmlElement, helper


class MenuItems:
    def __init__(self, menu_items: List[dict]):
        self._menu_items = menu_items

    @classmethod
    def from_iterable(cls, data: Iterable) -> "MenuItems":
        return cls(list(data))

    def to_xml(self) -> XmlElement:
        doc, tag, _, _, _ = XmlDoc("MenuItems").ttaa()
        lang_attr = helper.xml_namespace("lang", "xml")

        for menu_item in self._menu_items:
            with tag("MenuItem", id=menu_item["id"]):
                for page_id in menu_item["pages"]:
                    tag("pageId", text=page_id)

                tag("style", text=menu_item["style"])

                for title in menu_item["title"]:
                    attrs = dict()
                    if "lang" in title:
                        attrs[lang_attr] = title["lang"]

                    tag("title", text=title["value"], **attrs)

                tag("searchText", text=menu_item["search_text"])
                tag("position", text=menu_item["position"])

                with tag("Companies"):
                    for permalink in menu_item["companies"]:
                        tag("id", text=permalink)

        return doc.result

    def __str__(self) -> str:
        return helper.xml_to_string(self.to_xml())
