# Copyright (C) 2020-2021 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.

"""
A class to hold topology geometries
"""
from typing import TYPE_CHECKING, Any, Dict, Union

from here.content.hmc.baseattributes import BaseLayer

if TYPE_CHECKING:
    from here.content.hmc.hmc import HMC


class TopologyGeometry(BaseLayer):
    """
    A class to hold topology geometries
    """

    def __init__(self, content: "HMC", layer_id: str):
        """
        Instantiate a TopologyGeometry object.

        :param content: instance of the HMC root class
        :param layer_id: layer ID
        """

        # call a parent constructor
        super().__init__(content, layer_id)

        # dictionary to hold segment objects, per partition
        self.segments: Dict[str, dict] = {}

        # dictionary to hold node objects, per partition
        self.nodes: Dict[str, dict] = {}

    def fill(self, pid):
        """
        Fetch tile objects for a given partition ID and fill segments and nodes dictionary
        if not already done

        :param pid: partition ID
        """
        # segments and nodes are filled at the same time
        # so checking segments should be sufficient
        if pid not in self.segments:

            # fetch partition
            partition = self.get_partition(pid)

            # fill segments dictionary
            self.segments[pid] = {}
            for seg in partition.segment:
                self.segments[pid][seg.identifier] = seg

            # fill nodes dictionary
            self.nodes[pid] = {}
            for node in partition.node:
                self.nodes[pid][node.identifier] = node

    def get_segments(self, pid) -> Union[dict, Any]:
        """
        Get segments for given partition ID and segment ID

        :param pid: partition ID
        :return: segment dict or an adapter-specific type
        """

        # fetch contents for this pid if not already done
        self.fill(pid)

        if self.adapter is None:
            return self.segments[pid]
        else:
            columns, data = self.get_tabular_data_segment(pid)
            return self.adapter.from_tabular(columns, data)

    def get_nodes(self, pid) -> Union[dict, Any]:
        """
        Get nodes for given partition ID and node ID

        :param pid: partition ID
        :return: node dict or an adapter-specific type
        """

        # fetch contents for this pid if not already done
        self.fill(pid)

        if self.adapter is None:
            return self.nodes[pid]
        else:
            columns, data = self.get_tabular_data_node(pid)
            return self.adapter.from_tabular(columns, data)

    def get_tabular_data_segment(self, pid):
        """
        Get tabular data from segment dict
        :param pid: partition ID
        :return: columns, data
        """
        data = []
        for sid, segment in self.segments[pid].items():
            data.append(
                (
                    pid,
                    segment.identifier,
                    segment.start_node_ref,
                    segment.end_node_ref,
                    segment.geometry,
                    segment.length,
                )
            )
        return (
            ("partitionId", "identifier", "start_node_ref", "end_node_ref", "geometry", "length"),
            data,
        )

    def get_tabular_data_node(self, pid):
        """
        Get tabular data from segment dict
        :param pid: partition ID
        :return: columns, data
        """
        data = []
        for nid, node in self.nodes[pid].items():
            data.append((pid, node.identifier, node.segment_ref, node.geometry))
        return ("partitionId", "identifier", "segment_ref", "geometry"), data
