import py
from mod_python import util
from decorators import *
from lxml import etree

"""Example set of PythonHandlers"""

# no trailing slashes for paths!!
SITEROOT = '/debris'
TEMPLATEDIR = '/var/www/debris/.templates'

# a set of decorators all handlers will get, note how we cache very 
# aggressively (which we may want to change if we have 'real' dynamic content,
# meaning content that changes even without form args, etc.)
def basestack(handler):
    @responsewriter
    @treetostring
    @cache(createkey=lambda r: (r.filename, r.path_info), 
            condition=lambda r: util.FieldStorage(r).keys() == [] and \
                                    py.path.local(r.filename).check(),
            checktype=lambda d: isinstance(d, etree._Element))
    @addlayout(SITEROOT, '%s/macro.html' % (TEMPLATEDIR,))
    @addstylesheets(SITEROOT, '/.theme/style.css')
    @addsidebar('%s/sidebar.html' % (TEMPLATEDIR,))
    @checkerrors
    @fulltext('/tmp/quicksearch', '%s/searchresults.html' % (TEMPLATEDIR,))
    @checknotfound
    def basestack_wrapper(request):
        return handler(request)
    return basestack_wrapper

# handle plain html files
@basestack
@cache(checktype=lambda d: isinstance(d, dict))
@treetodict(body='//body/*', head='//head/*')
@htmltotree
def htmlhandler(request):
    request.content_type = 'text/html; charset=UTF-8'
    return py.path.local(request.filename).read()

# handle rest files
@basestack
@cache(checktype=lambda d: isinstance(d, dict))
@treetodict(body='//body/*', head='//head/*')
@htmltotree
@resttohtml
def resthandler(request):
    request.content_type = 'text/plain; charset=UTF-8'
    return py.path.local(request.filename).read()

# handle images with thumbnail support, note how we cache both the image and
# the thumbnail
@basestack
@cache(condition=lambda r: 'thumbnail' in r.path_info.split('/'),
        checktype=lambda d: isinstance(d, str))
@thumbnail(150)
@cache()
def imagehandler(request):
    from mimetypes import guess_type
    fname = request.filename
    fpath = py.path.local(fname)
    request.content_type = guess_type(fname)[0]
    return fpath.read()
    
# the screenshots page
@basestack
@cache(checktype=lambda d: isinstance(d, dict))
@screenshots('%s/screenshots/' % SITEROOT, 
                '%s/screenshots.html' % (TEMPLATEDIR,))
@treetodict(body='//body/*', head='//head/*')
@htmltotree
@resttohtml
@directories('%s/dirlist.html' % (TEMPLATEDIR,))
def dirhandler(request):
    # return apache.DECLINED for everything, this should be registered only
    # for directories, which are handled by the 'directories' decorator
    return apache.DECLINED

