from django.conf import settings

import egonomy
from egonomy.auth import get_egonomy_token
import urlparse
import urllib


def egonomy_context(request):
    
    egonomy_url = getattr(settings, 'EGONOMY_URL', '')
    egonomy_token = get_egonomy_token(request)
    egonomy_token_name = ( getattr(settings, 'EGONOMY_TOKEN_NAME', 'egonomytoken') or 'egonomytoken')
    
    if egonomy_url and egonomy_token and egonomy_token_name:
        url_parts = list(urlparse.urlparse(egonomy_url))
        url_params = urlparse.parse_qs(url_parts[4],keep_blank_values=True)
        url_params[egonomy_token_name] = egonomy_token
        url_parts[4] = urllib.urlencode(url_params, doseq=True)
        egonomy_url = urlparse.urlunparse(url_parts)

    return {'VERSION': egonomy.get_version(), 'EGONOMY_URL': egonomy_url }

