from django.conf import settings
from django.utils.crypto import get_random_string

from egonomy.utils import unix_time, encodeAES, decodeAES
import requests


def get_egonomy_token(request):
    
    if request.user.is_authenticated():
        sessionid = request.session.session_key
        salt = get_random_string(length=getattr(settings, 'EGONOMY_SALT_LENGTH', 12))
        
        return encodeAES("|".join([sessionid,salt]))
    else:
        return None

#TODO : check
def parse_egonomy_token(token):
    
    #retore padding if needed
    token += "=" * ((4 - len(token) % 4) % 4)
    decoded_token =  decodeAES(str(token))
    sessionid, salt = decoded_token.split("|")
    
    return {'sessionid': sessionid, 'salt': salt}


def clean_egonomy_username(username, is_internal):
    prefix = settings.EGONOMY_USER_PREFIX
    return (prefix if ( prefix not in username and not is_internal) else "") + username

def get_http_session():
    
    s = requests.Session()
    
    http_auth = (getattr(settings, 'EGONOMY_HTTP_USER', None), getattr(settings,'EGONOMY_HTTP_PASSWORD', None))

    if http_auth[0] is not None and http_auth[1] is not None:
        s.auth = http_auth
    
    return s
