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

from .advert_data_list import AdvertDataList
from .advert_tags import AdvertTags
from .menu_items import MenuItems
from .pin_data_list import PinDataList
from .places import Places
from .polygons import Polygons


class Root:
    def __init__(
        self,
        advert_data_list: AdvertDataList,
        menu_items: MenuItems,
        places: Places,
        polygons: Polygons,
        pin_data_list: PinDataList,
        advert_tags: AdvertTags,
    ):
        self._advert_data_list = advert_data_list
        self._menu_items = menu_items
        self._advert_tags = advert_tags
        self._places = places
        self._polygons = polygons
        self._pin_data_list = pin_data_list

    @classmethod
    def from_dict(cls, data: dict) -> "Root":
        return cls(
            advert_data_list=AdvertDataList.from_iterable(data["advert_data_list"]),
            menu_items=MenuItems.from_iterable(data["menu_items"]),
            pin_data_list=PinDataList.from_iterable(data["pin_data_list"]),
            places=Places.from_iterable(data["places"]),
            polygons=Polygons.from_iterable(data["polygons"]),
            advert_tags=AdvertTags.from_iterable(data["advert_tags"]),
        )

    def to_xml(self) -> XmlElement:
        doc = XmlDoc("AdvertDataList", {None: "http://maps.yandex.ru/advert/1.x"})

        menu_items = self._menu_items.to_xml()
        if menu_items is not None and len(menu_items.getchildren()) > 0:
            doc.append(menu_items)

        for advert_data in self._advert_data_list.to_xml().getchildren():
            doc.append(advert_data)

        for element in (
            self._advert_tags.to_xml(),
            self._places.to_xml(),
            self._polygons.to_xml(),
            self._pin_data_list.to_xml(),
        ):
            if element is not None and len(element.getchildren()) > 0:
                doc.append(element)

        return doc.result

    def __str__(self) -> str:
        return helper.xml_to_string(self.to_xml(), xml_declaration=True)
