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

if not os.environ.has_key('HTTP_COOKIE'):
    Redirect(kLoginPage)

username=GetCookie('user')
if not username:
    Redirect(kLoginPage)

sys.stderr = sys.stdout
try:

    cfgfile = '%s%s/.prefs' % (kReportsDir, username)
    p = Prefs()

    f = cgi.FieldStorage()

    if f.has_key('submitday'):
        p.submitday = int(f['submitday'].value)

    if f.has_key('bugstat') and f['bugstat'].value == 'on':
        p.bugstat = 1
    if f.has_key('codestat') and f['codestat'].value == 'on':
        p.codestat = 1
    if f.has_key('revstat') and f['revstat'].value == 'on':
        p.revstat = 1
    if f.has_key('newstat') and f['newstat'].value == 'on':
        p.newstat = 1
    if f.has_key('autosubmit') and f['autosubmit'].value == 'on':
        p.autosubmit = 1
    if f.has_key('manager') and f['manager'].value == 'on':
        p.manager = 1
    if f.has_key('title'):
        p.title = f['title'].value
    if f.has_key('team'):
        p.team = string.split(f['team'].value)
    if f.has_key('rows'):
        p.rows = int(f['rows'].value)

    if f.has_key('sections'):
        sec=string.split(f['sections'].value, '\n')
        so = []
        for k in range(len(sec)):
            s = string.strip(sec[k])
            if len(s):
                res = string.split(s, ':', 1)
                so.append(res[0])
                p.sections[res[0]] = string.join(res[1:])
        p.sectionorder = string.join(so, ',')

    p.prefs = cfgfile
    p.save()

    # change passwd for this account...
    if f.has_key('current') and f.has_key('newpasswd'):
        passwdfile = '%s%s/.passwd' % (kReportsDir, username)
        # TODO check for existing passwd? maybe...
        CreateUser(username, f['newpasswd'].value, passwdfile)
except:
    print 'Content-type: text/html\n'
    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'


Redirect(kBaseLocation)
