from dexy.plugin import Command
from middleware import StaticMiddleware
import socket
import web

class ViewerCommand(Command):
    """
    Starts a web.py application which lets you preview the snippets generated
    by your previous dexy run.
    """
    aliases = ['viewer']
    NAMESPACE = 'viewer'

def viewer_command(
        port=8090 # Port on which to run the viewer
        ):
    """
    Starts a web.py application which lets you preview the snippets generated by your previous dexy run.
    """
    import app as viewer
    func = viewer.app.wsgifunc()
    server_address =("0.0.0.0", port)

    func = StaticMiddleware(func)
    func = web.httpserver.LogMiddleware(func)

    server = web.httpserver.WSGIServer(server_address, func)

    print "launching viewer at http://%s:%d/" % server_address
    print "type ctrl+c to stop the server."
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
    except socket.error:
        print "ERROR port %s already in use, server not started" % port

def ping_command():
    print "pong"
