#
# Copyright (c) Daniel Sheffield 2023
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
from typing import Dict

from .CachedLoadingPage import CachedLoadingPage

class Cache:
    def __init__(self, limit) -> None:
        self._cache: Dict[str, CachedLoadingPage] = dict()
        self._limit = limit

    def get(self, key: str) -> str:
        if key not in self._cache:
            return None
        
        page = self._cache[key]
        if page.stale:
            del self._cache[key]
            return None
        return page.value if page.loaded else page.update()
    
    def _enforce_limit(self, limit):
        for idx, (_, k) in enumerate(sorted([
                (v.age, k) for k, v in self._cache.items()
            ])):
            if idx >= limit: del self._cache[k]

    def _clear_stale(self):
        for k in [k for k, v in self._cache.items() if v.stale]:
            del self._cache[k]
    
    def add(self, key: str, page: CachedLoadingPage) -> str:
        self._clear_stale()
        self._enforce_limit(self._limit)
        self._cache[key] = page
        return page.value
    
    def remove(self, key: str):
        if key in self._cache:
            del self._cache[key]

