from hashlib import sha1
from random import random
from django.conf import settings
from django.core.cache import caches

from django.contrib.auth import get_user_model

User = get_user_model()

CACHE_PREFIX = getattr(settings, 'RPC_CACHE_PREFIX', 'RPC_SESSION')
CACHE_LIFETIME = getattr(settings, 'RPC_CACHE_LIFETIME', 30*3600)
CACHE_NAME = getattr(settings, 'RPC_CACHE_NAME', 'default')

cache = caches[CACHE_NAME]


def get_session(user):
    assert isinstance(user, User)
    return cache.get(_get_login_key(user.username + str(user.id)))


def get_session_by_token(token):
    return cache.get(_get_token_key(token))


def set_session(user):
    assert isinstance(user, User)

    login_key = _get_login_key(user.username + str(user.id))
    session = cache.get(login_key)
    if not session:
        while 1:
            token = sha1(str(random()).encode('utf-8')).hexdigest()
            token_key = _get_token_key(token)
            if not cache.get(token_key):
                break
        session = {'user': user, 'token': token}
    else:
        token_key = _get_token_key(session['token'])

    cache.set(login_key, session, CACHE_LIFETIME)
    cache.set(token_key, session, CACHE_LIFETIME)

    return session


def _get_token_key(token):
    return '%s_TOKEN_%s' % (CACHE_PREFIX, token)


def _get_login_key(login):
    return '%s_USER_%s' % (CACHE_PREFIX, login)
