# -*- 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 People Web"""

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


import glasnost.common.faults as faults
import glasnost.common.context as context

from glasnost.proxy.PeopleProxy import *

from ObjectsWeb import register, AdminMixin, BaseObjectWebMixin, \
        ObjectWebMixin, ObjectsWebMixin
from tools import *
import widgets

import copy


class AdminPeople(AdminMixin, AdminPeople):
    defaultGroupId_kind_widget_fieldLabel = N_('Default Group')
    defaultGroupId_kind_widgetName = 'SelectId'
register(AdminPeople)


class Person(ObjectWebMixin, Person):
    email_kind_widget_fieldLabel = N_('Email')
    email_kind_widget_size = 40
    email_kind_widgetName = 'Email' #'InputText'

    fingerprint_kind_widget_fieldLabel = N_('GnuPG Fingerprint')
    fingerprint_kind_widget_size = 60
    fingerprint_kind_widgetName = 'InputText'

    firstName_kind_widget_fieldLabel = N_('First Name')
    firstName_kind_widget_size = 40
    firstName_kind_widgetName = 'InputText'

    lastName_kind_widget_fieldLabel = N_('Last Name')
    lastName_kind_widget_size = 40
    lastName_kind_widgetName = 'InputText'

    memberOf = None
    memberOf_kind_importExport = 'private'
    memberOf_kind_stateInViewMode = 'read-only/hidden-if-empty'
    memberOf_kind_stateInEditMode = 'read-only'
    memberOf_kind_itemKind_valueName = 'Id'
    memberOf_kind_widget_fieldLabel = N_('Member of groups')
    memberOf_kindName = 'Sequence'

    nickname_kind_widget_fieldLabel = N_('Nickname')
    nickname_kind_widget_size = 40
    nickname_kind_widgetName = 'InputText'

    def getEditLayoutSlotNames(self, fields, parentSlot = None):
        slotNames = ObjectWebMixin.getEditLayoutSlotNames(
            self, fields, parentSlot = parentSlot)
        slotNames = slotNames[:]
        userId = context.getVar('userId')
        hiddenSlotNames = []
        if not userId:
            hiddenSlotNames = ['creationTime', 'modificationTime']
        hiddenSlotNames.append('memberOf')
        for slotName in hiddenSlotNames:
            if slotName in slotNames:
                slotNames.remove(slotName)
        return slotNames

    def getViewLayoutSlotNames(self, fields, parentSlot = None):
        slotNames = ObjectWebMixin.getViewLayoutSlotNames(
            self, fields, parentSlot = parentSlot)
        slotNames = slotNames[:]
        userId = context.getVar('userId')
        userToken = context.getVar('userToken')
        if not userToken:
            slotName = 'email'
            if slotName in slotNames:
                slotNames.remove(slotName)
        if not userToken or context.getVar('useCompactLayout', default = 0):
            for slotName in ('creationTime', 'modificationTime'):
                if slotName in slotNames:
                    slotNames.remove(slotName)
        return slotNames
register(Person)


class PeopleWeb(ObjectsWebMixin, PeopleProxy):
    def getObject_handleResult(self, lazyObject):
        object = PeopleProxy.getObject_handleResult(self, lazyObject)
        groupsProxy = getProxyForServerRole('groups')
        object.memberOf = groupsProxy.getObjectIdsWithContent(
                object.id, indirect = 1)
        return object

    def getSortedIds(self, objects):
        labels = {}
        for object in objects.values():
            labels[object.id] = object.getSortString()
        ids = objects.keys()
        ids.sort(
            lambda id1, id2, labels = labels:
            cmp(labels[id1], labels[id2]))
        return ids

    def submitAddObject(self, object):
        error = 0
        try:
            return ObjectsWebMixin.submitAddObject(self, object)
        except faults.DuplicateFullName, f:
            error = 1
            object.setError('self.lastName', f)
        except faults.DuplicateEmail, f:
            error = 1
            object.setError('self.email', f)
        except faults.DuplicateFingerprint:
            error = 1
            object.setError('self.fingerprint', f)

        if error:
            context.setVar('again', 1)
            context.setVar('error', 1)
            return self.editObject(object)

    def submitModifyObject(self, object):
        error = 0
        try:
            self.modifyPartialObject(object, object.getSlotToModifyNames())
        except faults.WrongVersion:
            error = 1
            object.setError('version', 1)
        except faults.DuplicateFullName, f:
            error = 1
            object.setError('self.lastName', f)
        except faults.DuplicateEmail, f:
            error = 1
            object.setError('self.email', f)
        except faults.DuplicateFingerprint, f:
            error = 1
            object.setError('self.fingerprint', f)

        if error:
            context.setVar('again', 1)
            context.setVar('error', 1)
            return self.editObject(object)

    def view(self, id):
        webTools.addContextualHeader('noindex')
        return ObjectsWebMixin.view(self, id)
    view.isPublicForWeb = 1

    def viewAll(self):
        context.push(_level = 'viewAll',
                     defaultDispatcherId = context.getVar('dispatcherId'))
        try:
            if not self.canGetObjects():
                return accessForbidden()
            webTools.addContextualHeader('noindex')
            partialObjects = self.getObjects(
                ['firstName', 'lastName', 'nickname'])
            layout = X.array()
            layout += X.asIs(_("""<p>
Note that user accounts should now be created from the
<a href="%s">identities page</a>.
</p>""") % X.roleUrl('identities'))
            ids = self.getSortedIds(partialObjects)
            layout += self.getObjectsLayout(partialObjects, ids, [])
            layout += self.getViewAllButtonsBarLayout()
        finally:
            context.pull(_level = 'viewAll')
        return writePageLayout(layout,
                self.getTranslatedObjectsNameCapitalized())
    viewAll.isPublicForWeb = 1

