"""
flask_caching.backends.simple
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The simple cache backend.

:copyright: (c) 2018 by Peter Justin.
:copyright: (c) 2010 by Thadeus Burgess.
:license: BSD, see LICENSE for more details.
"""

import logging
import warnings
from typing import Any

from cachelib import SimpleCache as CachelibSimpleCache
from flask import Flask

from flask_caching.backends.base import BaseCache

logger = logging.getLogger(__name__)


class SimpleCache(BaseCache, CachelibSimpleCache):
    """Simple memory cache for single process environments. All operations
    are protected by a :class:`threading.RLock`, making a cache instance safe
    to use from multiple threads within the same process.

    :param threshold: the maximum number of items the cache stores before
                      it starts deleting some.
    :param default_timeout: the default timeout that is used if no timeout is
                            specified on ``set``. A timeout of
                            0 indicates that the cache never expires.
    :param ignore_delete_many_errors: If set to ``False`` the ``delete_many``
                                      method raises a ``RuntimeError`` in case
                                      a key couldn't be deleted.
                                      Defaults to ``False``.
    :param ignore_errors: Deprecated alias for ``ignore_delete_many_errors``.

        .. deprecated:: 2.5.0
           Will be removed in the next version.
    """

    def __init__(
        self,
        threshold: int = 500,
        default_timeout: int = 300,
        ignore_delete_many_errors: bool = False,
        ignore_errors: bool | None = None,
    ) -> None:
        if ignore_errors is not None:
            warnings.warn(
                "'ignore_errors' is deprecated and will be removed in the next "
                "version. Use 'ignore_delete_many_errors' instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            ignore_delete_many_errors = ignore_errors

        CachelibSimpleCache.__init__(
            self,
            threshold=threshold,
            default_timeout=default_timeout,
            ignore_delete_many_errors=ignore_delete_many_errors,
        )

    @classmethod
    def factory(
        cls,
        app: Flask,
        config: dict[str, Any],
        args: list[Any],
        kwargs: dict[str, Any],
    ) -> "SimpleCache":
        kwargs.update(dict(threshold=config["CACHE_THRESHOLD"]))
        return cls(*args, **kwargs)
