"""
PySourceColorFilter

OVERVIEW:
This filter works in conjunction with M.E.Farmer's PySourceColor
module and the builtin StaticFilter included with CherryPy to serve
up colorized versions of Python source files.  It can be easily
integrated into an existing CherryPy powered site to provide convenient
colorized source access.

REQUIREMENTS:
CherryPy 2.1rc1 - http://www.cherrypy.org/
PySourceColor 2.0 - http://bellsouthpwp.net/m/e/mefjr75/

DETAILS:
Its constructor takes one argument, defaultVersion, which can be
either 'original' or 'colorized', to serve either original or
colorized versions of the file respectively.

The version can be further specified per request via a query string
parameter. For example,
"http://localhost:8080/source/spam.py?version=original"
will request the original version of the file, whatever the default
may be.

See the example at the bottom of the code for sample usage.

TODO:
* Modify the filter to do inline coloring of Python code in arbitrary
pages (perhaps delimited with customizable tags).

* Expose more of the features available in PySourceColor.py (header,
footer, color schemes, etc)

LICENSE (MIT, OSI approved):
Copyright (c) 2005 Christian Wyglendowski

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

import cherrypy
from cherrypy.lib.filter.basefilter import BaseFilter
import PySourceColor as psc

__version__ = '0.4'

class PySourceColorFilter(BaseFilter):
    def __init__(self, defaultVersion):
        "defaultVersion must be either 'original' or 'colorized'"
        if defaultVersion not in ('original', 'colorized'):
            raise ValueError("defaultVersion must be either 'original' or 'colorized'")
        self.defaultVersion = defaultVersion
    
    def beforeFinalize(self):
        # first, we bail out if the staticfilter is not on for this path
        if not cherrypy.config.get('staticFilter.on', False):
            return
        
        # if there is no body, what is the point - bail out here
        if not cherrypy.response.body:
            return

        # get the version of the file that we want to see - colorized or original        
        version = cherrypy.request.paramMap.get('version', self.defaultVersion)

        # if we got some weird value for version, go with the default
        if version not in ('original', 'colorized'):
            version = self.defaultVersion

        # if the request was for the original file, stop messing with it
        if version == 'original':
            return

        # if the colorized version was requested, colorize it!        
        elif version == 'colorized':
            origCode = "".join(cherrypy.response.body)
            junk, colorizedCode = psc.str2css(origCode)
            cherrypy.response.body = colorizedCode
            # set our content type to 'text/html' so it renders nice in the browser
            cherrypy.response.headerMap['Content-Type'] = 'text/html'
            # replace the content-length value that staticfilter worked into the response
            # leaving it will foul things up so let the user agent figure it out
            cherrypy.response.headerMap['Content-Length'] = None

if __name__ == '__main__':
    class Root:
        def index(self):
            return "the index"
        index.exposed = True

    class ColorizedSource:
        # let's make the standard source the default and the colorized
        # source available with the ?version=colorized query string.
        _cpFilterList = [PySourceColorFilter(defaultVersion='original')]

    cherrypy.root = Root()
    cherrypy.root.source = ColorizedSource()

    cherrypy.config.update({'/source':{
                                'staticFilter.on':True,
                                'staticFilter.dir':'.'
                                },
                            'global':{
                                'autoreload.on':False
                                }
                            })

    print """
*********************************************************************
Visit
http://localhost:8080/source/pysourcecolorfilter.py?version=colorized
and
http://localhost:8080/source/pysourcecolorfilter.py
to test the filter.
*********************************************************************
"""
    
    cherrypy.server.start()
    