from typing import Iterable, List

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


class AdvertDataList:
    def __init__(self, advert_data_list: List[dict]):
        self._advert_data_list = advert_data_list

    @classmethod
    def from_iterable(cls, data: Iterable[dict]) -> "AdvertDataList":
        return cls(list(data))

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

        for advert_data in self._advert_data_list:
            with tag("AdvertData"):
                for page_id in advert_data["pages"]:
                    tag("pageId", text=page_id)

                tag("logId", text=advert_data["log_id"])

                with tag("Tags"):
                    for name, value in sorted(advert_data["fields"].items()):
                        tag("field", text=value, name=name)

                with tag("Advert"):
                    tag("title", text=advert_data["title"])
                    tag("text", text=advert_data["text"])

                    disclaimer = advert_data.get("disclaimer")
                    tag_if("disclaimer", disclaimer, text=disclaimer)

                    phone = advert_data.get("phone", {})

                    with tag("OverrideMetadata"):
                        with tag("Phones"):
                            with tag("Phone", type="phone"):
                                if phone:
                                    tag("formatted", text=phone["formatted"])

                                    country = phone.get("country")
                                    tag_if("country", country, text=country)

                                    prefix = phone.get("prefix")
                                    tag_if("prefix", prefix, text=prefix)

                                    tag("number", text=phone["number"])

                highlighted = advert_data.get("highlighted")
                tag_if("highlighted", highlighted, text=highlighted)

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

        return doc.result

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