from mod_python import apache, util
import py
import sys
import handler_registry

def handler(request):
    """handler for Kupu website URLs"""

    filename = request.filename
    fpath = py.path.local(filename)
    if (fpath.check(dir=False) and 
            fpath.ext not in handler_registry.exthandlers):
        # let apache handle unknown file types
        return apache.DECLINED
    
    options = request.get_options()
    charset = options.get('charset', 'UTF-8')
    content_type = 'text/html; charset=%s' % (charset,)
    context = {'environ': {},
                'form': util.FieldStorage(request),
                'request': request,
                'headers': {'content-type': content_type},
                }
    #context['environ'].update(dict([(k.lower(), v) for k, v in
    #                            apache.build_cgi_env(request).items()]))
    
    handler = handler_registry.status404handler
    if fpath.check(dir=True):
        if fpath.basename in handler_registry.dirhandlers:
            handler = handler_registry.dirhandlers[fpath.basename]
        else:
            for default in [d.strip() for 
                            d in options['defaultindexes'].split(',')]:
                dpath = fpath / default
                if dpath.check(file=True):
                    filename = dpath
                    request.filename = str(dpath)
                    if dpath.ext in handler_registry.exthandlers:
                        handler = handler_registry.exthandlers[dpath.ext]
    elif fpath.check(file=True):
        handler = handler_registry.exthandlers[fpath.ext]
    try:
        content = handler(context)
    except:
        exc, e, tb = sys.exc_info()
        content = handler_registry.errorhandler(exc, e, tb, context)
        context['headers']['content-type'] = content_type
        del tb
    
    ct = context['headers'].pop('content-type')
    
    # only add the layout if the content type hasn't changed
    if ct == content_type: 
        # add navigation, layout, etc.
        content = handler_registry.macrohandler(context, content)
    
    request.content_type = ct
    for k, v in context['headers'].iteritems():
        request.headers_out['-'.join([x.capitalize() for 
                            x in k.split('-')])] = v
    request.write(content)
    return apache.OK

