from __future__ import annotations
import errno
import functools
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable

if TYPE_CHECKING:
    from qtpy.QtGui import QIcon

__all__ = ('decorator', 'memoize', 'interruptable')


def decorator(caller: Callable, func: Callable | None = None) -> Callable:
    """
    Create a new decorator

    decorator(caller) converts a caller function into a decorator;
    decorator(caller, func) decorates a function using a caller.

    """
    if func is None:
        # return a decorator
        @functools.wraps(caller)
        def _decorator(func, *dummy_args, **dummy_opts):
            @functools.wraps(func)
            def _caller(*args, **opts):
                return caller(func, *args, **opts)

            return _caller

        _decorator.func = caller
        return _decorator

    # return a decorated function
    @functools.wraps(func)
    def _decorated(*args, **opts) -> Any:
        return caller(func, *args, **opts)

    _decorated.func = func
    return _decorated


def memoize(func: Callable) -> Callable:
    """
    A decorator for memoizing function calls

    https://en.wikipedia.org/wiki/Memoization

    """
    func.cache = {}
    return decorator(_memoize, func)


def _memoize(func: Callable, *args, **opts) -> QIcon | bool | str:
    """Implements memoized cache lookups"""
    if opts:  # frozenset is used to ensure hashability
        key = (args, frozenset(list(opts.items())))
    else:
        key = args
    cache = func.cache  # attribute added by memoize
    try:
        result = cache[key]
    except KeyError:
        result = cache[key] = func(*args, **opts)
    return result


@decorator
def interruptable(func: Callable, *args, **opts) -> Any:
    """Handle interruptible system calls

    macOS and others are known to interrupt system calls

        https://en.wikipedia.org/wiki/PCLSRing
        http://en.wikipedia.org/wiki/Unix_philosophy#Worse_is_better

    The @interruptable decorator handles this situation

    """
    while True:
        try:
            result = func(*args, **opts)
        except OSError as e:
            if e.errno in (errno.EINTR, errno.EINVAL):
                continue
            raise e
        break
    return result
