import datetime
import os
import redis
import pickle
from esy.client import ESIClient
from esy.auth import ESIAuthenticator


class ESICache(object):
    def __init__(self, redis_url: str, redis_port: int, db: str):
        self._r = redis.Redis(host=redis_url, port=redis_port, db=db)
        # self._r = redis.StrictRedis(host=redis_url, port=redis_port, db=db)

    def get(self, key):
        # return pickle.loads(self._r[key])
        return pickle.loads(self._r.get(key))

    def set(self, key, data, cached_until: datetime.datetime):
        self._r.set(key, pickle.dumps(data), ex=cached_until - datetime.datetime.now(datetime.timezone.utc))

    def __contains__(self, item):
        # return item in self._r
        return self._r.exists(item)


esi_client_id = os.getenv('ESI_CLIENT_ID')
esi_secret_key = os.getenv('ESI_SECRET_KEY')

esi_cache = ESICache(redis_url=os.getenv("REDIS_URL"), redis_port=int(os.getenv("REDIS_PORT")), db="0")

esi_client = ESIClient.get_client(user_agent=os.getenv('ESI_USER_AGENT'), cache=esi_cache)
esi_auth = ESIAuthenticator()
