#!/usr/local/bin/python2.2
#!/usr/bin/env python
import cgi
import os
import pickle
import sys
import time
import cgitb; cgitb.enable()

import MySQLdb
import _mysql

import pdqboard
import pagedef


messageheader = \
"""<P CLASS="graphic">
Hello Class of '93!  Please feel free to use this site to post information about yourself and visit back frequently for updates about our upcoming reunion in July. We are trying to find people so PLEASE forward this website address to people from '93.
</P>

<P CLASS="graphic">
If you have any pictures from our High School days that you would like to have posted, please email them to <a href="mailto:kathy93@maxint.net">Kathy Caulkins </a href="mailto:kathy93@maxint.net"> at <a href="mailto:kathy93@maxint.net">kathy93@maxint.net</a href="mailto:kathy93@maxint.net">.
</P>

<P CLASS="graphic">
If you have specific questions about the reunion please contact <a href="mailto:dvacca@worldnet.att.net">David Vacca</a href="mailto:dvacca@worldnet.att.net"> at <a href="mailto:dvacca@worldnet.att.net">dvacca@worldnet.att.net</a href="mailto:dvacca@worldnet.att.net">.
</P>

<P CLASS="graphic">
If you have questions or problems regarding this website please contact <a href="mailto:kathy93@maxint.net">Kathy Caulkins </a href="mailto:kathy93@maxint.net"> at <a href="mailto:kathy93@maxint.net">kathy93@maxint.net</a href="mailto:kathy93@maxint.net">.
</P>
"""

messagefooter = \
"""
</body>
</html>
"""

def starttag(tag, attributes = {}):
    if attributes:
        retstr = "<" + tag
        for i in attributes.keys():
            retstr = retstr + " " + i + "=\"" + attributes[i] + "\""
        return retstr + ">"
    return "<" + tag + ">"

class message:
    def __init__(self, text, id, sender = None, subject = None, inreplyto = None):
        self.text = text
        self.id = id
        self.sender = sender
        self.subject = subject
        self.inreplyto = inreplyto
        self.replies = []
        date = time.localtime()
        self.date = str(date[1]) + '/' + str(date[2]) + '/' + str(date[0])

    def addreply(self, replyid):
        self.replies.append(replyid)

    def notrepr(self):
        retval =  starttag('P')
        retval += "Date:" + msg.date + "<BR>\n"
        if msg.sender:
            retval += "From:" + msg.sender + "<BR>\n"
        if msg.subject:
            retval += "Subject:" + msg.subject + "<BR>\n"
        print msg.text

def getlock(lockfile):
    try:
        lockfd = os.open(lockfile, os.O_CREAT | os.O_EXCL)
        return 1
    except OSError:
        time.sleep(3)
        try:
            lockfd = os.open(lockfile, os.O_CREAT | os.O_EXCL)
            return 1
        except OSError:
            print starttag('DIV', {'CLASS': 'message'})
            print starttag('P')
            print "Uh-oh! I can't lock the database. Please try again in a moment."
            print "</P>\n"
            print "</DIV>\n"
            return 0

def header(header = "header.html"):
    f = open(header)
    h = ""
    for i in f.readlines():
        h += i
    f.close()
    return h

def footer():
    return "</body>\n</html>\n"

def main():
    dbfile = "messagedb"

    form = cgi.FieldStorage(keep_blank_values = 1)

    try:
        #db = MySQLdb.connect(user = 'root', host = 'flytrap', passwd = '5a1o6P', db = "reunionfkhs93")
        db = MySQLdb.connect(user = 'root', unix_socket = '/tmp/mysql.sock', passwd = '5a1o6P', db = "reunionfkhs93")
        cur = db.cursor()
    except _mysql.OperationalError, e:
        print "Content-type: text/html\n\n" + header()
        print starttag('DIV', {'CLASS': 'message'})
        print starttag('P')
        print "Bad Mojo detected! Couldn't connect to the database! Please contact the site administrator.", e
        print "</P>\n"
        print "</DIV>\n"
        return

    if form.getfirst('message'):
        msg = pdqboard.message(form.getfirst('message'), None, form.getfirst('sender'), form.getfirst('subject'))
        cur.execute("insert into messagepickles values(NULL, %s);", pickle.dumps(msg))
        #print "Location:", 'http://' + os.environ["SERVER_NAME"] + os.environ["SCRIPT_NAME"], "\n\n",
        print "Location:", 'http://www2.maxint.net:8475' + os.environ["SCRIPT_NAME"], "\n\n",
        return

    print "Content-type: text/html\n\n" + header() + messageheader

    print starttag('DIV', {'CLASS': 'graphic'})
    print '<A HREF=".?listsize=all">Show All Messages</A> <A HREF=".">Top 10 Messages</A>'
    print "</DIV>\n"

    if form.getfirst('listsize') == 'all':
        query = "select pickle from messagepickles order by id desc;"
    else:
        query = "select pickle from messagepickles order by id desc limit 0, 10;"

    try:
        if cur.execute(query) == 0:
            print starttag('DIV', {'CLASS': 'message'})
            print starttag('P')
            print "There are currently no messages on the board."
            print "</P>\n"
            print "</DIV>\n"
            print footer()
            return
    except _mysql.MySQLError:
        print starttag('DIV', {'CLASS': 'message'})
        print starttag('P')
        print "Bad Mojo detected! There has been an error with the database. Please contact the database administrator."
        print "</P>\n"
        print "</DIV>\n"
        print footer()
        return

    for i in cur.fetchall():
        pkl = i[0]

        msg = pickle.loads(pkl)
        print starttag('DIV', {'CLASS': 'message'})
        print starttag('P', {'CLASS': 'fields'})
        print "Date:", msg.date, "<BR>"
        if msg.sender:
            print "From:", msg.sender, "<BR>"
        if msg.subject:
            print "Subject:", msg.subject, "<BR>"
        print "</P>"
        print starttag('P', {'CLASS': 'messagetext'})
        print msg.text
        print "</P>"
        print "</DIV>\n"

        print starttag('P')
        print "</P>\n"

    print starttag('DIV', {'CLASS': 'graphic'})
    print '<A HREF=".?listsize=all">Show All Messages</A> <A HREF=".">Top 10 Messages</A>'
    print "</DIV>\n"

    print starttag('P')
    print "</P>\n"

    print footer()

if __name__ == '__main__':
    main()
