#
# Copyright (c) Daniel Sheffield 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
from pytest import fixture
from time import time
from app.rest.Cache import Cache
from app.rest.CachedLoadingPage import (
    CachedLoadingPage,
)

@fixture
def cache():
    return Cache(0)

def test_add(cache: Cache):
    val = 'test-cached-value'
    key = 'test-key'
    assert cache.add(key, CachedLoadingPage(val, lambda _: None)) == val

def test_get(cache: Cache):
    val = 'test-cached-value'
    key = 'test-key'

    assert cache.get(key) is None

    assert cache.add(key, CachedLoadingPage(val, lambda q: q.put('next-val'))) == val
    assert cache.get(key) == 'next-val'

def test_remove(cache: Cache):
    val = 'test-cached-value'
    key = 'test-key'

    assert cache.get(key) is None
    assert cache.add(key, CachedLoadingPage(val, lambda q: q.put('next-val'))) == val
    cache.remove(key)
    assert cache.get(key) is None

def test_enforce_limit(cache: Cache):
    val = 'test-cached-value'
    key = 'test-key'
    assert cache.add(key, CachedLoadingPage(val, lambda _: None)) == val
    # adding more exceeds limit
    assert cache.add('other', CachedLoadingPage(val, lambda _: None)) == val
    assert cache.get(key) is None
    assert cache.get('other') == val

def test_clean_stale(cache: Cache):
    val = 'test-cached-value'
    key = 'test-key'
    page = CachedLoadingPage(val, lambda _: None)
    page._created = time() - 10*60
    # add stale page
    assert cache.add(key, page) == val
    assert cache.get(key) is None
    
    page = CachedLoadingPage(val, lambda _: None)
    assert cache.add(key, page) == val
    # make page stale
    page._created = time() - 10*60
    assert cache.get(key) is None

    page = CachedLoadingPage(val, lambda _: None)
    assert cache.add(key, page) == val
    # make page stale
    page._created = time() - 10*60
    # stale page is rotated out on addition
    assert cache.add('other', CachedLoadingPage(val, lambda _: None)) == val
    assert cache.get(key) is None
    assert cache.get('other') == val
