from dataclasses import dataclass
from typing import TypeVar

from adafri.cache import Cache
from adafri.utils import BaseClass

cache = Cache(max_size=1000, eviction_policy='lru', default_ttl=3600, enable_persistence=True, persistence_file='lib_cache_data.pkl')


ClassContructor = TypeVar('ClassContructor', bound='BaseClass')

@dataclass(init=False)
class CacheClass:
    def __init__(self, prefix: str, class_constructor: ClassContructor):
        self.class_constructor = class_constructor
        self.prefix = prefix
    def set(self, key, value, ttl=3600, prefix=None):
        if value is None:
            return
        cache_key = f"{self.prefix if prefix is None else prefix}:{key}"
        if cache.get(cache_key) is None:
            if getattr(value, 'to_dict', None) is not None:
                cache.set(cache_key, value.to_dict(), ttl=ttl)
            else:
                cache.set(cache_key, value, ttl=ttl)
        
    def get(self, key, prefix=None):
        cache_key = f"{self.prefix if prefix is None else prefix}:{key}"
        data_value = cache.get(cache_key)
        if data_value is not None:
            if isinstance(data_value, dict):
                if self.class_constructor is not None:
                    return self.class_constructor.from_dict(data_value)
            return data_value
        return None
