import diskcache as dc


# The super cache class
class Cache(object):
    def __init__(self, name):
        self.name = name

    def set(self, key: str, value):
        pass

    def get(self, key: str):
        pass


class DiskCache(Cache):
    def __init__(self, name):
        super().__init__(name)
        self.c = dc.Cache(self.name)

    def set(self, key: str, value):
        self.c[key] = value

    def get(self, key: str):
        return self.c.get(key)


class LoadingCache(DiskCache):

    def __init__(self, name):
        super().__init__(name)

    def get_or_load(self, key, load_func):
        """
        Gets the value from cache by cache and will load remote data automatically
        when the local cache is empty.
        :param key: The key of cache
        :param load_func: The function of loading data
        :return: The first param is cache value, the second value means whether to hit the cache.
        """
        if self.enabled_cache():
            result = self.get(key)
            if result:
                return result, True

        # loading data
        new_result = load_func()
        if self.enabled_cache():
            self.set(key, new_result)
        return new_result, False

    def enabled_cache(self):
        return True
