#
# 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.PageCache import PageCache
from app.rest.CachedLoadingPage import (
    CachedLoadingPage,
    STALE,
)

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

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

def test_get(cache: PageCache):
    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'), incremental=False)).value == val
    assert cache.get(key).value == 'next-val'

def test_remove(cache: PageCache):
    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'), incremental=False)).value == val
    cache.remove(key)
    assert cache.get(key) is None

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

def test_clean_stale(cache: PageCache):
    val = 'test-cached-value'
    key = 'test-key'
    page = CachedLoadingPage(val, lambda _: None, incremental=False)
    page._created = time() - STALE
    # add stale page
    assert cache.add(key, page).value == val
    assert cache.get(key) is None

    page = CachedLoadingPage(val, lambda _: None, incremental=False)
    assert cache.add(key, page).value == val
    # make page stale
    page._created = time() - STALE
    assert cache.get(key) is None

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