#! /usr/bin/python2.2

#------------------------------------------------------------------------
# name:
# author: 		J Skinner
# Date Written:	
# Purpose:
# Notes
#------------------------------------------------------------------------



#------------------------   GLOBALS  ------------------------------------

DEBUG_MAIN = 0
DEBUG = 0
IS_CGI = 1
IS_DB = 1

#------------------------   IMPORTS  ------------------------------------

import string
import os
import sys

import cgi
import traceback

import access

#import cookie
from auth import Auth
from page import Page
from the_form import The_Form
from constants import *

#------------------------    GLOBALS   ----------------------------------

HEADER_BLOCK = '''\
Content-type: text/html
%(cookie)s

'''
#------------------------    CODE    ------------------------------------

def upload(db, auth, form_data):
    if form_data.filename:
        has_blob = 1
    else:
        has_blob = 0
        
    the_id = db.put('document_info', {'pub_date':form_data.pub_date,
        'title':form_data.title, 'short_desc':form_data.short_desc, 
        'long_desc':form_data.long_desc, 'has_blob':has_blob})
    if type(form_data.authors) is not type([]):
        db.put('doc_auth', {'document_id':str(the_id), 
            'author_id':str(form_data.authors)})
    else:
        for i in form_data.authors:
            db.put('doc_auth', {'doc_id':str(the_id), 'author_id':str(i)})
    
#    for i in [_i.strip() for _i in form_data.keywords.split(',')]:
#        try:
#            keyword_id = db.get('keywords', ['keyword_id'],
#                where='keyword="%s"'%i)
#        except db.NO_DATA:
#            keyword_id = db.put('keywords', {'keyword':i})
#        db.put('kw_doc', {'doc_id':the_id, 'keyword_id':keyword_id})

    print 'content-type: text/html'
    print
    print form_data.filename_name
    db.put('document_data', {'doc_id':the_id, 'the_doc':form_data.filename,
        'filename':form_data.filename_name})

    form_data.action = 'upload_success'
    return 1, UPLOAD_SUCCESS

def get_xtra_info(form):
    xtra_info = {}
    for i in form.keys():
        try:
            xtra_info[i] = form[i].value
    
        except:
            print 'content-type: text/html'
            print
            print form[i]
            print i
    if xtra_info != {}:
        return xtra_info
    else:
        return None
    

def main():
#    print 'Content-type: text/html'
#    print

    db = access.Access(dbname='pysocks', user='crypt')
    page_info = None

    form = cgi.FieldStorage()

    form_data = The_Form()
    form_data.get_values_from_form(form)
    auth = Auth(db, form_data)

    #status, page_id = auth.login_check()

    page_id = None

    xtra_info = get_xtra_info(form)

    if form_data.action == 'upload':
        res, page_id = upload(db, auth, form_data)
    elif form_data.action == 'download':
        the_page = Page(1, db, auth, page_info, xtra_info)
        return

    if form_data.action == 'show_author':
        page_id = 800

    if form.has_key('page') or form.has_key('action'):
        if page_id == None: page_id =form['page'].value
        the_page = Page(page_id, db, auth, page_info, xtra_info)

    else:
        # render the default page
        the_page = Page(1, db, auth, page_info, xtra_info)



    # output the actual page


    the_page.show()
#------------------------------------------------------------------------

if (DEBUG_MAIN):
    try:
        main()
    except SystemExit:
        pass
    except:
        # errMessage("an unkown error has occurred program terminating")
        sys.stderr = sys.stdout
        print '\n\n<PRE>'
        traceback.print_exc()
else:
    main()

#------------------------     END    ------------------------------------
