#!/usr/bin/env python2.5
# coding: utf-8
"""


"""

revision = "$Id: wiki_scribe.py,v 1.5 2008-06-06 02:09:45 sandro Exp $"

import time
import sys
import os

import html as h
import chatevents
import meeting


# this should of course come from the wiki....
users = [
    'Michel Dumontier',
    'Alan Rector', 
    'Christine Golbreich',
    'Jie Bao',
    'Matthew Horridge', 
    'Carsten Lutz',
    'Jeremy Carroll',
    'Martin Dzbor',
    'Thomas Schneider',
    'Sean Bechhofer',
    'Sebastian Brandt',
    'Dimitri Tsarkov',
    'Michael Schneider',
    'Jonathan Rees',
    'Vojtech Svatek',
    'Peter Haase',
    'Fabien Gandon',
    'Ratnesh Sahay',
    'Vit Novacek',
    'Zhe Wu',
    'Diego Calvanese',
    'Conrad Bock',
    'Anne Cregan',
    'Bernardo Cuenca Grau',
    'Achille Fokoue',
    'Enrico Franconi',
    'Sandro Hawke',
    'James Hendler',
    'Ivan Herman',
    'Pascal Hitzler',
    'Rinke Hoekstra',
    'Ian Horrocks',
    'Vipul Kashyap',
    'Elisa Kendall',
    'Markus Krötzsch',
    'Doug Lenat',
    'Joanne Luciano',
    'Deborah McGuinness',
    'Tommie Meyer',
    'Boris Motik',
    'Fabian Neuhaus',
    'Jeff Pan',
    'Bijan Parsia',
    'Peter (pfps) Patel-Schneider',
    'Alan Ruttenberg',
    'Uli Sattler',
    'Michael Sintek',
    'Evren Sirin',
    'Michael Smith',
    'Giorgos Stamou',
    'Giorgos Stoilos',
    'Suzette Stoutenburg',
    'Evan Wallace',
    ]


#
# GLOBAL VARIABLES
#
# (This is a CGI, we can do this kind of stuff.  Heh.  Maybe someday
# we'll turn this into a class called, um, ... Page? )
#
page = None
class State: pass
state = State()             # in the CGI sense; what we want carried
                            # from click to click via query or post
                            # parameters

mypath = "me"        # should be overrided via CGI

def startPage(title):
    global page
    if page == None:
        page = h.Document()
        page.head.append(h.title(title))
        # tinkering would be easier if we generated the style on a
        # callback, but we'd really need to give out good caching info
        #   page.head.append(h.stylelink("http://www.w3.org/2002/05/semwalker/walkerstyle.css"))
        # page.append(h.h1(title))



def prompt():
    print "Content-Type: text/html; charset=utf-8\n"
    startPage("scribealot")	
    form = h.form(method="GET", class_="f")	
    form << h.p("Where is the chat log:") 
    form << h.input(value="http://www.w3.org/2007/OWL/wiki/Chatlog_2008-06-04",
                    type="text",
                    size="72",
                    name="source")
    form <<  h.input(type="submit", name="Go",
                     value="Go")
    page << form
    # page << h.p("NOTE: THIS TAKES ABOUT A MINUTE.  BE PATIENT.")

    print page
    # cgi.print_environ()    

def generate_page(source):
    import os
    import tempfile

    tracefile = tempfile.NamedTemporaryFile().name
    docfile = tempfile.NamedTemporaryFile().name
    docfile2 = tempfile.NamedTemporaryFile().name

    redirect_stderr(tracefile)

    prolog = '/usr/local/bin/pl'
    script = '/u/home/sandro/cvs/dev.w3.org/2007/groupdev/wiki_tr.pl'
    #    code= os.spawnl(os.P_WAIT,
    #              prolog,
    #              '-g', """['%s'], go('%s', '%s'), halt""" % (script, source, tmp),
    #              ),
    cmd = ("""%s -L4M -q -g "['%s'], go('%s', '%s'), halt." """ %
           (prolog, script, source, docfile))
    code = os.system(cmd),
    # print "Done with ", cmd, " ** result: ", code

    num = "/usr/local/bin/num"
    toc = "/usr/local/bin/toc"
    cmd = ("""%s -l 2 < %s | %s -l 2 -h 6 -x -t > %s""" %
           (num, docfile, toc, docfile2))
    code = os.system(cmd)

    print "Content-Type: text/html; charset=utf-8\n"
    cat(docfile2)
    print "<hr /><h2>END OF DOCUMENT.   WIKI-TR diagnostics:</h2><pre>"
    cat(tracefile)
    print "</pre>"

def cat(filename):
    result_file = open(filename, "r")
    print result_file.read()
    result_file.close()
    

def generate_page2(source):
    print "Content-Type: text/html; charset=utf-8\n"

    allPeople = [meeting.Person(x) for x in users]
    m = meeting.Meeting(allPeople)
    count = 0

    assert source.startswith("http://")
    for c in chatevents.fromWikiRRSAgent(source):
        count += 1
        m.addChatEvent(c)

    d = h.Document()
    d.head << h.title("Meeting Record")
    d.head << h.stylelink("http://www.w3.org/2008/06/scribe.css")
    d << m.toHTML()
    print d
    


def ensure_safety(uri):
    for x in ['"', "'", " "]:
        if uri.find(x) > -1:
            print "The string %s contains a %s" % (uri, x)
            raise ValueError

def redirect_stderr(file):
    """Change stderr (file descriptor 2) from whatever it is now
    (probably apache) to the given file."""
    
    import os

    os.close(2)
    os.open(file, os.O_RDWR | os.O_CREAT, 0777)

def cgiMain():

    import cgi
    import sys
    import os

    form = cgi.FieldStorage()
    source=form.getfirst("source")
    if source is None or source == "":
        prompt()
    else:
        ensure_safety(source)
        generate_page2(source)

