from socket import gethostbyname, gaierror

from .settings import CACHE, CACHE_TIMEOUT, get_key


class Cache(object):
    @staticmethod
    def get(token, ip):
        if CACHE_TIMEOUT:
            return CACHE.get(get_key(token, ip))

    @staticmethod
    def set(token, ip, access):
        if CACHE_TIMEOUT:
            CACHE.set(get_key(token, ip), access, CACHE_TIMEOUT)

    @staticmethod
    def delete(token, ip):
        CACHE.delete(get_key(token, ip))

    @staticmethod
    def clear():
        CACHE.clear()


cache = Cache()
del Cache
drop_cache_ip = cache.delete


def drop_cache_token(token, ips, hostnames):
    _ips = list(ips) if ips else []
    # resolve hostnames to IPs
    if hostnames:
        for hostname in hostnames:
            try:
                ip = gethostbyname(hostname)
            except gaierror:
                continue
            _ips.append(ip)
    # drop cache for all IPs
    for ip in _ips:
        cache.delete(token, ip)
