# 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 Associated Segments from Navigation Attributes and Environmental Zones Layers.
"""
from dataclasses import dataclass
from typing import Dict, Iterable, 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.hmc2.base_attributes import (
    Attribute,
    BaseAttributesMultiLayerBinding,
    SegmentRef,
)
from here.content.hmc2.environmental_zones import EnvironmentalZones, Zone
from here.content.hmc2.topology_attributes import TopologyAttributes
from here.platform.adapter import Adapter, Partition


@dataclass
class SegmentToEnvironmentalZone:
    """Segment to Ennvironmental Zone"""

    partition_id: Partition
    segment_ref: SegmentRef
    forward: bool
    backward: bool
    applies_to: Dict[str, bool]
    zone: Zone

    indexer = ContentIndexer(
        partition="partition_id",
        refs={
            "location": lambda a: [r for r in a.zone.location_ref],  # type: ignore # noqa: E501
            "segment": lambda a: a.segment_ref.ref,  # type: ignore
        },
    )


class EnvironmentalZoneConditions(BaseAttributesMultiLayerBinding):
    """class to associate segment with environmental zones"""

    _content: ParentContent

    def __init__(self, content: ParentContent, layer_id: str, adapter: Optional[Adapter] = None):
        """
        Instantiate an class Multilayer EnvironmentalZones 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)
        EnvironmentalZoneConditions._content = content

    @classmethod
    def schema_hrn(cls) -> List[str]:
        """
        :return: the HRN of schema this binding can parse and index
        """

        return TopologyAttributes.schema_hrn()
        # return [
        #    f"hrn:here:schema:::com.here.schema.rib:navigation-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 {
            "environmental_zones": EnvironmentalZones(
                content=cls._content, layer_id="environmental-zones"
            )
        }

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

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

    @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, "environmental_zone_condition")

        parsed_and_indexed = super().parse_and_index(partition_id, msg)

        environmental_zone_condition = parsed_and_indexed.objects("environmental_zone_condition")

        segment_to_environmental_zones: list = cls.associate_ezc_ez(
            environmental_zone_condition, partition_id
        )

        return ContentPartition(cls, segment_to_environmental_zone=segment_to_environmental_zones)

    @classmethod
    def associate_ezc_ez(
        cls, environmental_zone_condition: Iterable[object], partition_id: str
    ) -> List[SegmentToEnvironmentalZone]:
        """
        Associate environmental_zone_condition with environment_zone.

        :param environmental_zone_condition: a dict of segment to environmental zone condition.
        :param partition_id: partition id of the base layer.
        :return: list of SegmentToEnvironmentalZone object.
        """

        environmental_zones = cls.associated_layers()["environmental_zones"]

        ez = environmental_zones.get(partition="all", object_type="zone")

        key_ezr = "environmental_zone_ref"
        key_id = "identifier"

        segment_to_environmental_zones: list = [
            SegmentToEnvironmentalZone(
                partition_id=partition_id,
                segment_ref=segment,
                forward=ezc.forward,  # type: ignore
                backward=ezc.backward,  # type: ignore
                applies_to=ezc.attribute["applies_to"],  # type: ignore
                zone=ez[ezc.attribute[key_ezr][key_id]],  # type: ignore
            )
            for ezc in environmental_zone_condition
            for segment in ezc.segments  # type: ignore
        ]

        return segment_to_environmental_zones
