from operator import itemgetter
from typing import Iterable, List

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


class Polygons:
    def __init__(self, polygons: List[dict]):
        self._polygons = polygons

    @classmethod
    def from_iterable(cls, data: Iterable) -> "Polygons":
        return cls(sorted(data, key=itemgetter("id")))

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

        for polygon in self._polygons:
            with tag("Polygon"):
                tag("id", text=polygon["id"])
                tag("polygon", text=polygon["polygon"])

        return doc.result

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