from operator import attrgetter
from typing import Iterable, List, Union

from maps_adv.export.lib.core.client.old_geoadv import OrgPlace
from maps_adv.export.lib.core.xml import XmlDoc, XmlElement, helper
from maps_adv.points.proto.primitives_pb2 import Point


class Places:
    def __init__(self, places: List[Union[OrgPlace, Point]]):
        self._places = places

    @classmethod
    def from_iterable(cls, data: Iterable[Union[OrgPlace, Point]]):
        return cls(sorted(data, key=attrgetter("id")))

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

        for place in self._places:
            with tag("Place"):
                tag("id", text=place.id)
                tag("latitude", text=place.latitude)
                tag("longitude", text=place.longitude)

                for address in place.address:
                    if address["value"]:
                        attrs = dict()
                        if "lang" in address:
                            attrs[lang_attr] = address["lang"]

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

                for title in place.title:
                    if title["value"]:
                        attrs = dict()
                        if "lang" in title:
                            attrs[lang_attr] = title["lang"]

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

                if place.permalink is not None:
                    tag("permalink", text=place.permalink)

        return doc.result

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