"""Utility functions for use in templates / controllers

*PLEASE NOTE*: Many of these functions expect an initialized RequestConfig
object. This is expected to have been initialized for EACH REQUEST by the web
framework.

"""
import os
import re
import urllib
from routes import request_config

def _screenargs(kargs):
    """
    Private function that takes a dict, and screens it against the current 
    request dict to determine what the dict should look like that is used. 
    This is responsible for the requests "memory" of the current.
    """
    config = request_config()
    if config.mapper.explicit and config.mapper.sub_domains:
        return _subdomain_check(config, kargs)
    elif config.mapper.explicit:
        return kargs
    
    controller_name = kargs.get('controller')
    
    if controller_name and controller_name.startswith('/'):
        # If the controller name starts with '/', ignore route memory
        kargs['controller'] = kargs['controller'][1:]
        return kargs
    elif controller_name and not kargs.has_key('action'):
        # Fill in an action if we don't have one, but have a controller
        kargs['action'] = 'index'
    
    memory_kargs = getattr(config, 'mapper_dict', {}).copy()
    
    # Remove keys from memory and kargs if kargs has them as None
    for key in [key for key in kargs.keys() if kargs[key] is None]:
        del kargs[key]
        if memory_kargs.has_key(key):
            del memory_kargs[key]
    
    # Merge the new args on top of the memory args
    memory_kargs.update(kargs)
    
    # Setup a sub-domain if applicable
    if config.mapper.sub_domains:
        memory_kargs = _subdomain_check(config, memory_kargs)
    
    return memory_kargs

def _subdomain_check(config, kargs):
    """Screen the kargs for a subdomain and alter it appropriately depending
    on the current subdomain or lack therof."""
    if config.mapper.sub_domains:
        subdomain = kargs.pop('sub_domain', None)
        if isinstance(subdomain, unicode):
            subdomain = str(subdomain)
        fullhost = config.environ.get('HTTP_HOST') or \
            config.environ.get('SERVER_NAME')
        hostmatch = fullhost.split(':')
        host = hostmatch[0]
        port = ''
        if len(hostmatch) > 1:
            port += ':' + hostmatch[1]
        sub_match = re.compile('^.+?\.(%s)$' % config.mapper.domain_match)
        domain = re.sub(sub_match, r'\1', host)
        if subdomain and not host.startswith(subdomain) and \
            subdomain not in config.mapper.sub_domains_ignore:
            kargs['_host'] = subdomain + '.' + domain + port
        elif (subdomain in config.mapper.sub_domains_ignore or \
            subdomain is None) and domain != host:
            kargs['_host'] = domain + port
        return kargs
    else:
        return kargs
    

def _url_quote(string, encoding):
    """A Unicode handling version of urllib.quote_plus."""
    if encoding:
        return urllib.quote_plus(unicode(string).encode(encoding), '/')
    else:
        return urllib.quote_plus(str(string), '/')