# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


__doc__ = """Glasnost Sessions Page"""

__version__ = '$Revision$'[11:-2]


import time

import glasnost.common.context as context
from glasnost.common.translation import languageKeys
import glasnost.common.xhtmlgenerator as X

import glasnost.web.calendaring
from glasnost.web.tools import *


def index():
    identitiesProxy = getProxyForServerRole('identities')
    if not identitiesProxy.isAdmin():
        return accessForbidden()
    sessionsProxy = getProxyForServerRole('sessions')
    history = sessionsProxy.getHistory()
    layout = X.array()
    layout += X.h3(_('Active Sessions'))
    table = X.table(_class = 'objects-table')
    layout += table
    thead = X.thead()
    table += thead
    tr = X.tr()
    thead += tr
    tr += X.th(_('Start Time'))
    tr += X.th(_('Expiration Time'))
    tr += X.th(_('User'))
    tr += X.th(_('IP Address'))
    tbody = X.tbody()
    table += tbody
    history.sort(lambda x,y: -cmp(x['startTime'], y['startTime']))
    for session in [x for x in history if x.has_key('expirationTime')]:
        tr = X.tr()
        tr += X.td(time.strftime('%Y-%m-%d %H:%M',
                                 time.localtime(session['startTime'])))
        tr += X.td(time.strftime('%Y-%m-%d %H:%M',
                                 time.localtime(session['expirationTime'])))
        user = context.getVar('user')
        if user is None:
            tr += X.td()
        else:
            tr += X.td(user.getLabel())
        tr += X.td(session['ipAddress'])
        tbody += tr

    layout += X.h3(_('Previous Sessions'))
    table = X.table(_class = 'objects-table')
    layout += table
    thead = X.thead()
    table += thead
    tr = X.tr()
    thead += tr
    tr += X.th(_('Start Time'))
    tr += X.th(_('End Time'))
    tr += X.th(_('User'))
    tr += X.th(_('IP Address'))
    tbody = X.tbody()
    table += tbody
    for session in [x for x in history if x.has_key('endTime')]:
        tr = X.tr()
        tr += X.td(time.strftime('%Y-%m-%d %H:%M',
                                 time.localtime(session['startTime'])))
        tr += X.td(time.strftime('%Y-%m-%d %H:%M',
                                 time.localtime(session['endTime'])))
        user = context.getVar('user')
        if user is None:
            tr += X.td()
        else:
            tr += X.td(user.getLabel())
        tr += X.td(session['ipAddress'])
        tbody += tr

    return writePageLayout(layout, _('Sessions History'))

def month(year = '', month = ''):
    identitiesProxy = getProxyForServerRole('identities')
    if not identitiesProxy.isAdmin():
        return accessForbidden()

    if not year or not month:
        year, month = time.localtime()[:2]
    year, month = int(year), int(month)

    prevYear, prevMonth = year, month-1
    if prevMonth == 0:
        prevMonth, prevYear = 12, prevYear - 1
    nextYear, nextMonth = year, month+1
    if nextMonth == 13:
        nextMonth, nextYear = 1, nextYear + 1

    timeStart = time.mktime([year, month, 1] + [0] * 6)
    timeEnd = time.mktime([nextYear, nextMonth, 1] + [0] * 6)

    sessionsProxy = getProxyForServerRole('sessions')
    history = sessionsProxy.getHistory()

    class SessionStat:
        def getLabel(self):
            return self.number
        def getUrl(self):
            return None

    sessionsDict = {}
    for h in history:
        date = time.strftime('%Y-%m-%d', time.localtime(h['startTime']))
        if not sessionsDict.has_key(date):
            sessionsDict[date] = 0
        else:
            sessionsDict[date] += 1

    sessions = []
    for date, number in sessionsDict.items():
        s = SessionStat()
        s.date = time.mktime([int(x) for x in date.split('-')] + 6 * [0])
        s.number = number
        if number:
            sessions.append(s)

    monthLayout = glasnost.web.calendaring.getMonthLayout(
            year, month, X.actionUrl('month'), sessions, 'date')
    
    return writePageLayout(monthLayout, _('Sessions History (month view)'))

