# Copyright (C) 2021-2023 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 Composite road attributes.
"""

from dataclasses import dataclass
from typing import Dict, List, Mapping, Optional

from google.protobuf.message import Message
from here.content.base import ContentIndexer, ContentPartition, SingleLayerBinding
from here.content.content import Content as ParentContent
from here.content.content import hmc_schema_version
from here.content.hmc2.adas_attributes import SegmentAnchor
from here.content.hmc2.base_attributes import BaseAttributesMultiLayerBinding
from here.content.hmc2.topology_geometry import Node, TopologyGeometry
from here.content.utils.proto import decode_message
from here.platform.adapter import Adapter, DecodedMessage, Identifier, Partition


@dataclass
class ComplexIntersectionAttribute:
    """Complex Intersection Attribute"""

    partition_id: Partition
    complex_intersection_id: Identifier
    node_anchors: List[DecodedMessage]
    segment_anchors: List[DecodedMessage]
    indexer = ContentIndexer(partition="partition_id", identifier="complex_intersection_id")


@dataclass
class ComplexRoadAttribute:
    """Complex Road Attribute"""

    partition_id: Partition
    complex_road_id: Identifier
    segment_anchors: List[DecodedMessage]
    start_complex_intersection_ref: DecodedMessage
    end_complex_intersection_ref: DecodedMessage
    indexer = ContentIndexer(partition="partition_id", identifier="complex_road_id")


@dataclass
class ComplexObjectAttribute:
    """Complex Object Attribute"""

    partition_id: Partition
    complex_object_id: Identifier
    node_anchors: List[DecodedMessage]
    segment_anchors: List[DecodedMessage]
    name: List[DecodedMessage]
    valid_unnamed: bool
    anchor_point: DecodedMessage
    indexer = ContentIndexer(partition="partition_id", identifier="complex_object_id")


class CompositeRoadAttribute(BaseAttributesMultiLayerBinding):
    """Class to associate composite road attributes and topology geometry"""

    _content: ParentContent

    def __init__(self, content: ParentContent, layer_id: str, adapter: Optional[Adapter] = None):
        """
        Instantiate a class Composite Road Attribute binding.
        Assign content to Class attribute _content.

        :param content: Content object that references a catalog at a fixed version
        :param layer_id: ID of the only layer that contains the content
        :param adapter: the ``Adapter`` to transform data between different representations,
            ``None`` to use the adapter defined in ``content``.
        """
        super().__init__(content, layer_id, adapter)
        CompositeRoadAttribute._content = content

    @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:complex-road-attributes_v2:
            {hmc_schema_version}"""
        ]

    @classmethod
    def associated_layers(cls) -> Dict[str, SingleLayerBinding]:
        """
        Provide associated dependent/independent layers to the base layer.

        :return: dict of key as single layer and value as SingleLayerBinding Object.
        """
        return {
            "topology_geometry": TopologyGeometry(
                content=cls._content, layer_id="topology-geometry"
            )
        }

    @classmethod
    def object_types(cls) -> Mapping[str, type]:
        """
        :return: the types of attributes supported by this binding
        """
        return {
            "complex_road_attribute": ComplexRoadAttribute,
            "complex_intersection_attribute": ComplexIntersectionAttribute,
            "complex_object_attribute": ComplexObjectAttribute,
        }

    @classmethod
    def _internal_object_types(cls) -> Mapping[str, type]:
        """
        :return: the types of attributes supported by this binding
        """
        return {}

    @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, "complex_road_attribute")
        assert hasattr(msg, "complex_intersection_attribute")
        assert hasattr(msg, "complex_object_attribute")

        topology_layer = cls.associated_layers()["topology_geometry"]
        nodes = topology_layer.get(partition_id, "node")
        segments = topology_layer.get(partition_id, "segment")

        def parse_node_anchors(node_indices: List[int]) -> List[Node]:
            return [node_anchor[index] for index in node_indices]

        def parse_segment_anchors(segment_indices: List[int]) -> List[SegmentAnchor]:
            return [segment_anchor[index] for index in segment_indices]

        node_anchor = [
            nodes[p.node_ref.partition_name][p.node_ref.identifier]
            if nodes[p.node_ref.partition_name]
            else None
            for p in msg.node_anchor  # type: ignore
        ]

        segment_anchor = [
            SegmentAnchor(
                partition_id=Partition(partition_id),
                oriented_segment_ref=[
                    (
                        segments[n.segment_ref.partition_name][n.segment_ref.identifier],
                        n.inverted,
                    )
                    if segments[n.segment_ref.partition_name]
                    else None
                    for n in p.oriented_segment_ref
                ],
                first_segment_start_offset=decode_message(p.first_segment_start_offset),
                last_segment_end_offset=decode_message(p.last_segment_end_offset),
                attribute_orientation=str(p.attribute_orientation),
            )
            for p in msg.segment_anchor  # type: ignore
        ]

        complex_intersection_attribute = [
            ComplexIntersectionAttribute(
                partition_id=Partition(partition_id),
                complex_intersection_id=Identifier(p.identifier),
                node_anchors=parse_node_anchors(p.node_anchor_index),
                segment_anchors=parse_segment_anchors(p.segment_anchor_index),
            )
            for p in msg.complex_intersection_attribute  # type: ignore
        ]
        complex_object_attribute = [
            ComplexObjectAttribute(
                partition_id=Partition(partition_id),
                complex_object_id=Identifier(p.identifier),
                node_anchors=parse_node_anchors(p.node_anchor_index),
                segment_anchors=parse_segment_anchors(p.segment_anchor_index),
                name=p.name,
                valid_unnamed=bool(p.valid_unnamed),
                anchor_point=decode_message(p.anchor_point),
            )
            for p in msg.complex_object_attribute  # type: ignore
        ]

        complex_road_attribute = [
            ComplexRoadAttribute(
                partition_id=Partition(partition_id),
                complex_road_id=Identifier(p.identifier),
                segment_anchors=parse_segment_anchors(p.segment_anchor_index),
                start_complex_intersection_ref=decode_message(p.start_complex_intersection_ref),
                end_complex_intersection_ref=decode_message(p.end_complex_intersection_ref),
            )
            for p in msg.complex_road_attribute  # type: ignore
        ]

        return ContentPartition(
            cls,
            complex_road_attribute=complex_road_attribute,
            complex_intersection_attribute=complex_intersection_attribute,
            complex_object_attribute=complex_object_attribute,
        )
