#!/usr/bin/python

# Authors:
#   Jason Gerard DeRose <jderose@redhat.com>
#
# wehjit: A Python web-widget library
# Copyright (C) 2009  Red Hat
#
# This file is part of `wehjit`.
#
# `wehjit` is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# `wehjit` is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# `wehjit`.  If not, see <http://www.gnu.org/licenses/>.

"""
An interactive tour of the `wehjit` library.
"""

import sys
import os
from os import path
import optparse


# Check for dependencies:
error = """
%(eclass)s: %(emsg)s
Error: %(script)s requires the Python `%(package)s` package
To install `%(package)s`, see %(url)s
"""

script = path.basename(sys.argv[0])

requirements = [
    ('paste', 'http://pythonpaste.org/'),
    ('genshi', 'http://genshi.edgewall.org/'),
    ('pygments', 'http://pygments.org/'),
    ('assetslib', 'http://jderose.fedorapeople.org/assets/'),
]

fail = False
for (package, url) in requirements:
    try:
        __import__(package)
    except ImportError, e:
        fail = True
        print error % dict(package=package, url=url, script=script,
            eclass=e.__class__.__name__, emsg=str(e)
        )
if fail:
    sys.exit(1)


# On with the show!
import paste.httpserver
from paste.urlmap import URLMap
import paste.gzipper
from assetslib import Assets
from assetslib.wsgi import AssetsApp
import wehjit


# Parse some command line options
parser = optparse.OptionParser(
	version='%%prog %s' % wehjit.__version__,
)
parser.add_option('--out',
    help='Directory to render static files (default=static)',
    default='static',
)
parser.add_option('--static',
    help='Render demo to a static .xhtml files',
    default=False,
    action='store_true',
)
parser.add_option('--html',
    help='Serialize to HTML instead of XHTML',
    default=False,
    action='store_true',
)
parser.add_option('--dev',
    help='Run in development mode (requires FireBug)',
    default=True,
    action='store_false',
    dest='prod',
)
parser.add_option('--host',
    help='Listen on address HOST (default=127.0.0.1)',
    default='127.0.0.1',
)
parser.add_option('--port',
    help='Listen on PORT (default=8080)',
    default=8080,
    type='int',
)

(options, args) = parser.parse_args()
kw = dict()
if options.html:
    kw['serializer'] = 'html'
if options.static:
    kw['static'] = True


widgets = wehjit.Collection('widget-demo')
widgets.register_builtins()
if options.static:
    if path.lexists(options.out):
        print 'Error: output directory already exists:'
        print '    %r' % options.out
        print 'Not rendering static .xhtml files'
        sys.exit(1)
    app = wehjit.Application('', widgets=widgets, prod=options.prod, **kw)
else:
    app = wehjit.Application('/', widgets=widgets, prod=options.prod, **kw)


# Populate the Application with pages:
example_pages = []
examples = tuple(wehjit.iter_page_examples())
for (name, module) in examples:
    # Create the page
    page = module.create_page(app)
    if page is None:
        continue
    example_pages.append(page)
    if name == 'e0_welcome':
        page.id = ''
    else:
        page.id = name
    page.title = module.title

    # Create the source code page:
    fname = name + '.py'
    src = path.join(path.dirname(path.abspath(module.__file__)), fname)
    assert path.isfile(src)
    code = app.new('PageApp',
        title=fname,
        id=':'.join([name, 'code']),
    )
    code.menuset.add(
        app.new('MenuItem', label='< Back', href=page.url)
    )
    code.actions.add(
        app.new('HighlighterThemeChanger')
    )
    code.view.add(
        app.new('Highlighter',
            lexer='python',
            code=open(src, 'r').read(),
        )
    )

    # Add a link to the code page:
    page.menuset.add(
        app.new('MenuItem',
            label='Source Code',
            href=code.url,
            title='Click to see source code for this example',
        )
    )


# Build the 'Examples' menu on each example page:
for page in example_pages:
    page.menu.label = 'Examples'
    for p in example_pages:
        page.menu.add(
            app.new('MenuItem', label=p.title, href=p.url)
        )

# Finalize the Application:
app.render_assets()
app.finalize()


if options.static:
    app.render_static(options.out)
else:
    assetsapp = AssetsApp(app.assets)

    urlmap = URLMap()
    urlmap[app.url] = app
    urlmap[assetsapp.url] = assetsapp

    # Start the paste WSGI server:
    paste.httpserver.serve(
        paste.gzipper.middleware(urlmap),
        host=options.host,
        port=options.port,
    )
