# Copyright (C) 2021-2022 HERE Global B.V. and its affiliate(s).
# All rights reserved.
#
# This software and other materials contain proprietary information
# controlled by HERE and are protected by applicable copyright legislation.
# Any use and utilization of this software and other materials and
# disclosure to any third parties is conditional upon having a separate
# agreement with HERE for the access, use, utilization or disclosure of this
# software. In the absence of such agreement, the use of the software is not
# allowed.

"""
Bindings for the HMC Topology Geometry.
"""
from dataclasses import dataclass
from typing import List, Mapping, Optional, Union

from google.protobuf.message import Message
from here.content.base import ContentIndexer, ContentPartition, SingleLayerBinding
from here.content.content import hmc_schema_version
from here.content.hmc2.place_context import PlaceClassification, PlaceContext
from here.content.utils.proto import (
    decode_enum,
    decode_enum_array,
    decode_message,
    parse_ref,
    value_or_None,
)
from here.platform.adapter import DecodedMessage, Identifier, Partition


@dataclass
class StreetName:
    """Street Name"""

    partition_id: Partition
    street_id: Identifier
    street_name: List[DecodedMessage]
    indexer = ContentIndexer(partition="partition_id", identifier="street_id")


@dataclass
class StreetSection:
    """Street section"""

    partition_id: Partition
    streetsection_id: Identifier
    street_index: Union[int, None]
    administrative_context_index: int
    associated_street_section_index: List[DecodedMessage]
    government_code: Optional[str] = None
    indexer = ContentIndexer(partition="partition_id", identifier="streetsection_id")


class StreetNames(SingleLayerBinding):
    """
    Bindings for the HMC street names.
    """

    @classmethod
    def schema_hrn(cls) -> List[str]:
        """
        :return: the HRN of schema this binding can parse and index
        """
        return [f"hrn:here:schema:::com.here.schema.rib:street-names_v2:{hmc_schema_version}"]

    @classmethod
    def object_types(cls) -> Mapping[str, type]:
        """
        :return: the types of attributes supported by this binding
        """
        return {"street": StreetName, "context": PlaceContext, "street_section": StreetSection}

    @classmethod
    def parse_and_index(cls, partition_id: str, msg: Message) -> ContentPartition:
        """
        Parse and index decoded message.

        :param partition_id: identifier of the partition
        :param msg: decoded content from the layer, in the form of a Protobuf message
        :return: the content of a partition parsed and indexed in its own data structure
        """
        assert hasattr(msg, "street")
        assert hasattr(msg, "administrative_context")
        assert hasattr(msg, "street_section")

        street = [
            StreetName(
                partition_id=Partition(partition_id),
                street_id=Identifier(p.identifier),
                street_name=[decode_message(n) for n in p.street_name],
            )
            for p in msg.street  # type: ignore
        ]

        def parse_classifications(cs) -> List[PlaceClassification]:
            return [
                PlaceClassification(
                    preference=decode_enum(c, "preference"), place_ref=parse_ref(c.place_ref)
                )
                for c in cs
            ]

        context = [
            PlaceContext(
                classification_type=decode_enum(ctx, "classification_type"),
                city=parse_classifications(ctx.city),
                postal_code=parse_classifications(ctx.postal_code),
                country=parse_classifications(ctx.country),
                state=parse_classifications(ctx.state),
                region=parse_classifications(ctx.region),
                county=parse_classifications(ctx.county),
                district=parse_classifications(ctx.district),
                sub_district=parse_classifications(ctx.sub_district),
                further_zone=parse_classifications(ctx.further_zone),
                default_mapping=int(ctx.default_mapping),
                political_view=decode_enum_array(ctx, "political_view", False),
                political_view_exception=decode_enum_array(ctx, "political_view_exception", False),
            )
            for ctx in msg.administrative_context  # type: ignore
        ]
        street_section = [
            StreetSection(
                partition_id=Partition(partition_id),
                streetsection_id=Identifier(street_sec.identifier),
                administrative_context_index=street_sec.administrative_context_index,
                government_code=str(street_sec.government_code),
                street_index=value_or_None(street_sec, "street_index"),
                associated_street_section_index=[
                    n for n in street_sec.associated_street_section_index
                ],
            )
            for street_sec in msg.street_section  # type: ignore
        ]
        return ContentPartition(cls, street=street, context=context, street_section=street_section)
