import os, posixpath

from rlextra.utils.cgisupport import BorgTimeStamp

def uniqueFilename(prefix=None, suffix=None, ext='.pdf', hostname=None, appName=None):
    bts = BorgTimeStamp(pfx=prefix,sfx=suffix,appName=appName,hostname=hostname)
    bts.reset()
    id = bts.currentId
    return id+ext

def fullUniqueFilenameAndUrlPath(prefix=None, suffix=None, ext='.pdf', hostname=None, appName=None):
    from django.conf import settings
    fn = uniqueFilename(prefix, suffix, ext, hostname, appName)
    return os.path.join(settings.OUTDIR, fn), posixpath.join(settings.OUTDIR_HTTP, fn)

def assertedMedia(css, js):
    from django.conf import settings
    from django.forms import Media
    from os.path import join, isfile
    
    class MediaConfigurationError(Exception):
        pass

    fnames = list(js)
    for l in css.itervalues():
        fnames.extend(l)
    for fname in fnames:
        p = join(settings.MEDIA_ROOT, fname)
        if not isfile(p):
            # Because for some obscure reason django swallows any kind of exception raised in here,
            # we have to miss-use JS for this purpose:
            return "<script language=\"javascript\">alert('Could not find %p which is needed by this application.')</script>" % p
    return Media(css=css, js=js)

def deepDecode(x, encoding='utf-8'):
    '''
    Convert all 8-bit strings found in structure x to unicode.
    Supports list tuple and dict structures.
    Needed to workaround a limitation of simplejson 1.5 which does not decode 8-bit strings.
    '''
    if isinstance(x, str):
        return x.decode(encoding)
    elif isinstance(x, tuple):
        return tuple( deepDecode(item, encoding) for item in x )
    elif isinstance(x, list):
        return [ deepDecode(item, encoding) for item in x ]
    elif isinstance(x, dict):
        return dict([ (key, deepDecode(val, encoding)) for key, val in x.items() ])
    else:
        return x

def deepEncode(x, encoding='utf-8'):
    '''
    Convert all unicode strings found in structure x to utf-8 strings.
    Supports list and dict structures. Also encodes dict keys!
    '''
    if isinstance(x, unicode):
        return x.encode(encoding)
    elif isinstance(x, tuple):
        return tuple( deepEncode(item, encoding) for item in x )
    elif isinstance(x, list):
        return [ deepEncode(item, encoding) for item in x ]
    elif isinstance(x, dict):
        return dict([ (deepEncode(key, encoding), deepEncode(val, encoding)) for key, val in x.items() ])
    else:
        return x
