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

"""
Item extracters for the HMC Layers.
"""

from typing import Any, Dict, List


class CachedExtracter:
    """
    Caches the already requested item from the collection.
    This way items requested repeatedly from the collection
    can be called fetched once from the it and reused.
    """

    def __init__(self, collection: List[Any]):
        """
        Initializes the CachedExtracter.

        :param collection: List of given items.
        """

        self.collection = collection
        self.cache: Dict[int, Any] = {}

    def get(self, index: int):
        """
        Gets the item from the cache. If it is absent in the cache,
        item from the collection is fetched and cached.

        :param index: index against which item needs to be fetched and/or cached.
        :return: the item against the index.
        """

        if index not in self.cache:
            self.cache[index] = self.collection[index]
        return self.cache[index]
