from collections import namedtuple
from typing import Union

from maps_adv.export.lib.core.client.old_geoadv import OrgPlace
from maps_adv.points.client.lib import ResultPoint

GenericPlace = namedtuple(
    "GenericPlace", ("id", "address", "latitude", "longitude", "title", "permalink")
)


async def place_transform(place: Union[OrgPlace, ResultPoint]) -> GenericPlace:
    fields = {
        "id": None,
        "title": [],
        "address": [],
        "latitude": None,
        "longitude": None,
        "permalink": None,
    }
    if isinstance(place, ResultPoint):
        fields.update(
            {
                "id": str(place.id),
                "latitude": place.latitude,
                "longitude": place.longitude,
            }
        )

    elif isinstance(place, OrgPlace):
        fields.update(
            {
                "id": f"altay:{place.permalink}",
                "latitude": place.latitude,
                "longitude": place.longitude,
                "permalink": place.permalink,
            }
        )
        for field in ("title", "address"):
            value = getattr(place, field)
            if isinstance(value, dict):
                new_value = list(
                    {"lang": lang, "value": text} for lang, text in value.items()
                )
            else:
                new_value = [{"value": value}]

            fields[field] = new_value

    else:
        raise RuntimeError("Unsupported place info type: {}".format(type(place)))

    return GenericPlace(**fields)
