#!/usr/bin/python
import cgi, os, sys, re, traceback
from utils import *
from cookie import *
from konst import *
from prefs import *

# weekend is historical.... 
f = cgi.FieldStorage()
if f.has_key('viewtype'):
    viewtype = f['viewtype'].value
elif not f.has_key('from'):
    Redirect(kBaseLocation)

showconf = 0
weekend=''
if f.has_key('from'):
    weekend=f['from'].value

if f.has_key('conf') and f['conf'].value == 'on':
    showconf = 1

if not f.has_key('user'):
    username = GetCookie('user')
else:
    username = f['user'].value
if not username:
    Redirect(kLoginPage)

showgrp=0
if f.has_key('team') and f['team'].value == 'on':
    showgrp=1

viewstyle = None
if f.has_key('viewstyle') and showgrp:
    viewstyle= f['viewstyle'].value

print 'Content-Type: text/html\n'

sys.stderr = sys.stdout

if not os.access('%s%s' % (kReportsDir, username), os.F_OK):
    print """<H3>No such user!</H3>"""
    sys.exit(0)

showcurrent=0
lastweek=0
if viewtype == 'bydate': 
    submittedOn = weekend
elif viewtype == 'last':
    submittedOn = LastSubmitted(username)
elif viewtype == 'lastweek':
    lastweek = 1
    submittedOn = LastSubmitted(username, lastweekonly=1)
elif viewtype == 'current':
    submittedOn = ''
    showcurrent = 1

prefs = Prefs('%s%s/.prefs' % (kReportsDir, username))
grp = IfElse(showgrp, '%s\'s' % IfElse(len(prefs.title), prefs.title, '%s\'s group' % username), '%s\'s' % username)

print '<HTML><HEAD><TITLE> %s weekly status ' % grp
print '</TITLE><LINK REL=STYLESHEET HREF="reports.css"></HEAD>'

# PrintFile('header.inc')
# don't print the image for the final form
print """
<BODY BGCOLOR="#EEEEEE" TEXT="#000000" LINK="#000099" ALINK="#FF0000">
<TABLE WIDTH="80%" HEIGHT="100%" VALIGN="MIDDLE" ALIGN="CENTER" BORDER=0>
<TR><TD align=center>
"""

print '<CENTER><H3>%s weekly status</H3>' % grp
print IfElse(showcurrent, '<H4>for this week</H4></CENTER><TABLE>',
    '<H4>submitted on %s</H4></CENTER><TABLE>' % submittedOn)

p = LastSubmitted(username, rel=1, reldt=weekend)
n = LastSubmitted(username, rel=2, reldt=weekend)
if showcurrent: n = None
if p or n: print '<h4 align=right>'
if p:
    print '<a href="show.cgi?user=%s&viewtype=bydate&from=%s&team=%s&conf=%s">Prev</a>' % \
        (username, p,
            IfElse(showgrp, "on", "off"), 
            IfElse(showconf, "on", "off"))
if not showcurrent and (p or n) and not showgrp:
    print '<a href="show.cgi?user=%s&viewtype=current&team=%s&conf=%s">Current</a>' % \
        (username, IfElse(showgrp, "on", "off"), IfElse(showconf, "on", "off"))
if n:
    print '<a href="show.cgi?user=%s&viewtype=bydate&from=%s&team=%s&conf=%s">Next</a>' % \
        (username, n, IfElse(showgrp, "on", "off"), IfElse(showconf, "on", "off"))


def printLI(user, filename, section=None):
    if not section: section = user
    if os.access(filename, os.F_OK) and os.stat(filename)[6]:
        print '<LI>%s' % section
        PrintFile(filename, 1, showconf)

repdir = IfElse(showcurrent, '%s/%s' % (kReportsDir, username),
    '%s%s/old/%s' % (kReportsDir, username, submittedOn))
try:
    splitchar = ' '
    if ',' in prefs.sectionorder: splitchar = ','
    files = IfElse(showcurrent, string.split(prefs.sectionorder, splitchar),
        os.listdir(repdir))
    tmpfiles = []
    # Remove the ones that we don't care about
    for k in files:
        if k == 'old' or k[0] == '.' or string.rfind(k, '.bak') != -1 : continue
        tmpfiles.append(k)
        
    files = tmpfiles
    if not viewstyle:
        for k in files: 
            # skip over in current case
            # also skip over backup files
            ourfile = '%s/%s' % (repdir, k)

            if showgrp and prefs.manager and len(prefs.team):
                try:
                    print '<TR><TD><B>%s</B></TD></TR><TR><TD>' % prefs.sections[k]
                except KeyError: # in case someone changed sections
                    print '<TR><TD><B>%s</B></TD></TR><TR><TD>' % k
                if k != 'summary': print '<UL>'
                for member in prefs.team:
                    ls = None
                    if viewtype == 'bydate':
                        ls = LastSubmitted(member, reldt=weekend, rel=1)
                    else:
                        ls = LastSubmitted(member, lastweek)
                    if ls:
                        file = '%s%s/old/%s/%s' % (kReportsDir, member, ls, k)
                        printLI(member, file)
                # don't print names for summary section--
                if k == 'summary':
                    PrintFile(ourfile, 1, showconf)
                else:
                    printLI(username, ourfile)
                    print '</UL>'
            else:
                if os.access(ourfile, os.F_OK) and os.stat(ourfile)[6]:
                    try:
                        print '<TR><TD><B>%s</B></TD></TR><TR><TD>' % \
                            prefs.sections[k]
                    except KeyError: # in case someone changed sections
                        print '<TR><TD><B>%s</B></TD></TR><TR><TD>' % k
                    PrintFile(ourfile, 1, showconf)
                    print '</TD></TR>'
    elif viewstyle=='on':
        #our own stuff..
        print '<TR><TD><B>%s</B></TD></TR><TR><TD><UL>' % username
        for k in files:
            ls = None
            if viewtype== 'bydate':
                ls = LastSubmitted(username, reldt=weekend, rel=1)
            else:
                ls = LastSubmitted(username, lastweek)
            if ls:
                file = '%s%s/old/%s/%s' % (kReportsDir, username, ls, k)
                try: printLI(username, file, prefs.sections[k])
                except KeyError: pass
        for member in prefs.team:
            print '<TR><TD><B>%s</B></TD></TR><TR><TD><UL>' % member
            for k in files:
                ls = None
                if viewtype == 'bydate':
                    ls = LastSubmitted(member, reldt=weekend, rel=1)
                else:
                    ls = LastSubmitted(member, lastweek)
                if ls:
                    file = '%s%s/old/%s/%s' % (kReportsDir, member, ls, k)
                    try: printLI(member, file, prefs.sections[k])
                    except: pass
            print '</UL></TD></TR>'
            
except OSError:
    print '<H3>No status report found by that date!</H3>'
except:
    print '\n\n<H3>Oops! something bad happened... contact '
    print '<A HREF="mailto:leaf@mozilla.org">leaf</A></H3>'
    print '\n\n<PRE>'
    print '-'*60
    traceback.print_exc()
    print '-'*60
    print '\n</PRE>\n'

print '</TABLE> </FORM> </CENTER>'
if showcurrent and not showgrp:
    print '<p align=right><A href="/reports/"><b>Edit</b></a></p>'
PrintFile('footer.inc')
