# vim:smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class:ts=4:sts=4:sta:et:ai:shiftwidth=4
# Copyright (C) 2005 Canonical Limited
#       Authors: Robert Collins <robert.collins@canonical.com>
#
# This program 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 2 of the License, or
# (at your option) any later version.

# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys

from twisted.application import internet, service
from twisted.internet import protocol, reactor, defer
from twisted.protocols import basic
from twisted.web import resource, server, static
import cgi

import pqm
import logging
import time

class QueueResource(resource.Resource):
    """A resource that shows a PQM queue."""

    def __init__(self, queue):
        self.queue = queue
        resource.Resource.__init__(self)

    def getChild(self, path, request):
        """Get a child of the queue"""
        if path:
            return static.Data("<h1>Please visit the root</h1>", 'text/html')
        text = "<h1>PQM Queue: %d scripts</h1>" % len(self.queue.messages)
        text += "<p>Current time: %s UTC</p>" % cgi.escape(
            time.ctime(time.time()))
        text += "<ol>"
        for message in self.queue.messages:
            text += "<li><p>%s: %s, '%s' <ol>" % (
                cgi.escape("%s UTC" % time.ctime (message.getSubmissionTime())),
                cgi.escape(message.getSender()),
                cgi.escape(message.getSubject()))
            for command in message.getCommands():
                text += "<li>%s</li>" % cgi.escape(command)
            text += "</ol></p></li>" 
        text += "</ol>"
        return static.Data(text, 'text/html')

class PQMInfo(object):

    def __init__(self, filenames):
        self.filenames = filenames
        self.messages = []

    def refresh(self):
        configp = pqm.ConfigParser()
        configp.read(self.filenames)
        queuedir = pqm.get_queuedir(configp, logging, [])
        self.messages = pqm.find_patches(queuedir, logging, False)
        try:
            [message.getSender() for message in self.messages]
        except:
            # We dont care about exceptions in getSender() here - 
            # we are just preseeding the files to reduce the race
            # condition with script completion.
            pass

application = None
def main(argv):
    global application
    application = service.Application('pqm')
    pqminfo = PQMInfo(pqm.configfile_names)
    serviceCollection = service.IServiceCollection(application)
    internet.TCPServer(8000, server.Site(QueueResource(pqminfo))
        ).setServiceParent(serviceCollection)
    internet.TimerService(30, pqminfo.refresh).setServiceParent(serviceCollection)
    
if __name__ == '__builtin__':
    main(sys.argv)
