from typing import Iterable, List

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


class AdvertTags:
    def __init__(self, advert_tags: List[dict]):
        self._advert_tags = advert_tags

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

    def to_xml(self) -> XmlElement:
        doc, tag, _, _, _ = XmlDoc("AdvertTags").ttaa()

        for advert_tag in self._advert_tags:
            with tag("AdvertTag", id=advert_tag["id"]):
                with tag("Companies"):
                    for permalink in sorted(advert_tag["companies"]):
                        tag("id", text=permalink)

        return doc.result

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