# -*- 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.

from __future__ import nested_scopes

__doc__ = """Glasnost Calendar Web Tools"""

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


import glasnost.common.context as context
import glasnost.common.xhtmlgenerator as X

from glasnost.web.tools import *

import calendar
import time

dayLabels = [ N_('Monday'), N_('Tuesday'), N_('Wednesday'), N_('Thursday'),
              N_('Friday'), N_('Saturday'), N_('Sunday') ]
    
monthLabels = [N_('January'), N_('February'), N_('March'),
               N_('April'), N_('May'), N_('June'),
               N_('July'), N_('August'), N_('September'),
               N_('October'), N_('November'), N_('December') ]

# Note to translators: those are "in sentence" labels, capitalized in
# English but not in (some) other languages
monthLabelsNoCapitalization = [
            N_('xJanuary'), N_('xFebruary'), N_('xMarch'),
            N_('xApril'), N_('xMay'), N_('xJune'),
            N_('xJuly'), N_('xAugust'), N_('xSeptember'),
            N_('xOctober'), N_('xNovember'), N_('xDecember') ]

def getMonthLabel(monthNumber):
    return _(monthLabels[monthNumber-1])

def getMonthLabelNoCapitalization(monthNumber):
    return _(monthLabelsNoCapitalization[monthNumber-1])[1:]
    
def getMonthLayout(year, month, role, objects, startSlot, endSlot = None):
    table = X.table(_class = 'calendar-month-full')
    
    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

    caption = X.caption()
    caption += X.a(
            href = X.roleUrl(role, '%d/%d' % (prevYear, prevMonth)),
            _class = 'previous-month')('<<')
    caption += X.span()('%s %s' % (_(monthLabels[month-1]), year))
    caption += X.a(
            href = X.roleUrl(role, '%d/%d' % (nextYear, nextMonth)),
            _class = 'next-month')('>>')
    table += caption

    tr = X.tr()
    for wd in dayLabels:
        tr += X.th(scope = 'col')(_(wd))
    table += X.thead(tr)
    
    cal = calendar.monthcalendar(year, month)

    if not endSlot:
        endSlot = startSlot
    
    today = list(time.localtime(time.time())[:3])

    tbody = X.tbody()
    table += tbody
    for i in range(len(cal)):
        tr = X.tr()
        tbody += tr

        for j in range(len(cal[i])):
            d = cal[i][j]
            if d == 0:
                dayLabel = ''
                tr += X.td(_class = 'noday')
                continue
            else:
                dayLabel = str(d)
            thisDate = [year, month, d]
            nextDate = [year, month, d+1]
            dayContent = X.array()
            dayContent += X.span(_class = 'day-title')(dayLabel)
            timeStart = time.mktime(thisDate + [0]*5 + [time.localtime()[-1]])
            timeEnd = time.mktime(nextDate + [0]*5 + [time.localtime()[-1]])
            dayObjects = [x for x in objects if \
                        getattr(x, startSlot) < timeEnd and \
                        ((getattr(x, endSlot) is None and 
                          getattr(x, startSlot) >= timeStart ) or \
                         getattr(x, endSlot) >= timeStart)]
            dayObjects.sort(lambda x,y: cmp(getattr(x, startSlot),
                                            getattr(y, startSlot)))
            if len(dayObjects):
                ul = X.ul()
                for d in dayObjects:
                    li = X.li()
                    if hasattr(d, 'id'):
                        dayLabel = getObjectLabelTranslated(
                            d.id, context.getVar('readLanguages'))
                        li += X.a(href = X.idUrl(d.id))(dayLabel)
                    else:
                        url = d.getUrl()
                        if url:
                            li += X.a(href = url)(d.getLabel())
                        else:
                            li += d.getLabel()
                    ul += li
                dayContent += ul
            className = ''
            if thisDate == today:
               className = 'today'
            elif thisDate < today:
                className = 'past'
            else:
                className = 'future'
            className += ' d%d' % (j+1)
            if j in (5, 6):
                className += ' weekend'
            tr += X.td(_class = className)(dayContent)
    
    return table

def getSmallMonthLayout(year, month, role, objects, startSlot, endSlot = None):
    table = X.table(_class = 'calendar-month-small')
    
    # no <caption> here; I had trouble formatting it
    caption = X.tr(X.th(colspan = 7)(
        X.a(href = X.roleUrl(role, '%d/%d' % (year, month)))(
                '%s %s' % (_(monthLabels[month-1]), year)) ))
    table += caption

    tr = X.tr()
    for wd in dayLabels:
        tr += X.th(scope = 'col')(_(wd)[0])
    table += tr
    
    cal = calendar.monthcalendar(year, month)

    if not endSlot:
        endSlot = startSlot
    
    today = list(time.localtime(time.time())[:3])

    tbody = X.tbody()
    table += tbody
    for i in range(len(cal)):
        tr = X.tr()
        tbody += tr

        for j in range(len(cal[i])):
            d = cal[i][j]
            if d == 0:
                dayLabel = ''
                tr += X.td(_class = 'noday')
                continue
            else:
                dayLabel = str(d)
            thisDate = [year, month, d]
            nextDate = [year, month, d+1]
            timeStart = time.mktime(thisDate + [0]*5 + [time.localtime()[-1]])
            timeEnd = time.mktime(nextDate + [0]*5 + [time.localtime()[-1]])
            dayObjects = [x for x in objects if \
                        getattr(x, startSlot) < timeEnd and \
                        ((getattr(x, endSlot) is None and 
                          getattr(x, startSlot) >= timeStart ) or \
                         getattr(x, endSlot) >= timeStart)]
            dayObjects.sort(lambda x,y: cmp(getattr(x, startSlot),
                                            getattr(y, startSlot)))

            dayContent = dayLabel
            classNames = []
            if len(dayObjects):
                classNames.append('day-with-event')
                # TODO: sth with dayObjects (title attribute ?)
                # dayContent = X.a...
                if len(dayObjects) == 1:
                    href = X.idUrl(dayObjects[0].id)
                else:
                    href = X.roleUrl(role, '%d/%d/%d' % (year, month, d))
                    dayLabel = getObjectLabelTranslated(
                            d.id, context.getVar('readLanguages'))
                dayContent = X.a(href = href,
                    title = ', '.join([getObjectLabelTranslated(x.id,
                        context.getVar('readLanguages')) for x in dayObjects]))(
                    dayLabel)
                
            if thisDate == today:
               classNames.append('today')
            elif thisDate < today:
                classNames.append('past')
            else:
                classNames.append('future')
            classNames.append('d%d' % (j+1))
            if j in (5, 6):
                classNames.append('weekend')
            tr += X.td(_class = ' '.join(classNames))(dayContent)
    
    return table


