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

"""
A class to hold address attributes
"""
from typing import Optional

from here.content.hmc.baseattributes import BaseLayer, RangedAttribute
from here.platform.adapter import Adapter


class AddressAttributes(BaseLayer):
    """
    A class to hold address attributes
    """

    def get_attribute(self, pid, attribute_name, adapter: Optional[Adapter] = None):
        """
        Get the attribute for given partitionId and attribute name
        Intended attributes: postal_code, administrative_context_attribute,
        address_range, street_section

        :param pid: a partition ID
        :param attribute_name: attribute collection name in the partition
        :param adapter: the ``Adapter`` to transform data between different representations,
            ``None`` to use the adapter defined in the constructor or, if unset, in ``content``.
        :return: attribute dict or an adapter-specific type
        """

        # first fill the attribute
        self.fill_attribute(pid, attribute_name)

        content_adapter = self._content_adapter(adapter)

        if attribute_name not in self.attributes or pid not in self.attributes[attribute_name]:
            return None

        if content_adapter is None:
            return self.attributes[attribute_name][pid]
        else:
            columns, data = self.get_tabular_data(pid, attribute_name)
            return content_adapter.from_tabular(columns, data)

    def fill_attribute(self, pid, attribute_name):
        """
        Fill the attribute for given attribute name
        Intended attributes: postal_code, administrative_context_attribute,
        address_range, street_section

        :param pid: a partition ID
        :param attribute_name: attribute collection name in the partition
        """

        # initialize self.attributes[attribute_name] container
        self.attributes.setdefault(attribute_name, {})

        # do nothing if pid is already filled
        if pid in self.attributes[attribute_name]:
            return

        # get partition object
        partition = self.get_partition(pid)

        if attribute_name in ("postal_code", "address_range"):
            self.resolve_address_range_postal_code(partition)
        else:
            # associate segments with attributes via segment_anchors
            attributes = self.resolve_single_segment_anchors(partition, attribute_name)

            # update attributes container
            self.attributes[attribute_name].update(attributes)

    def resolve_address_range_postal_code(self, partition):
        """
        Fill the attribute for postal_code
        Intended attributes: postal_code, address_range

        :param partition: a partition object
        """

        # initialize self.attributes container
        self.attributes.setdefault("postal_code", {})
        self.attributes.setdefault("address_range", {})

        # associate segments with attributes via segment_anchors
        address_range = self.resolve_single_segment_anchors(partition, "address_range")

        postal_code = {}
        for pid, segments in address_range.items():
            postal_code[pid] = {}
            for sid, directions in segments.items():
                postal_code[pid][sid] = {}
                for d, ras in directions.items():
                    postal_code[pid][sid][d] = []
                    for ra in ras:
                        pcs = []
                        for pm in ra.attribute.postal_mapping:
                            pcs.append(partition.postal_code[pm.postal_code_index])
                        postal_code[pid][sid][d].append(
                            RangedAttribute(ra.start_offset, ra.end_offset, pcs)
                        )
                    postal_code[pid][sid][d].sort(key=lambda x: x.start_offset)

        # update attributes container
        self.attributes["address_range"].update(address_range)
        self.attributes["postal_code"].update(postal_code)

    def get_tabular_data(self, pid, attribute_name):
        """
        Convert the given attribute to tabular data
        :param pid: partition ID
        :param attribute_name: attribute name to look for
        :return: columns, data
        """
        return self.get_tabular_data_from_single_segment(pid, attribute_name)
