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

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


import copy

import glasnost.common.context as context
import glasnost.common.faults as faults
import glasnost.common.tools_new as commonTools
import glasnost.common.xhtmlgenerator as X

import glasnost.proxy.modes as proxyModes

import things


register = things.register


class Aspect(things.ThingMixin, proxyModes.Aspect):
    kind = None # Not a slot
    slot = None # Not a slot.

    def isModelHidden(self):
        return self.state == 'hidden' \
               or self.state == 'read-only/hidden-if-empty' \
               and self.kind.modelValueIsEmpty(self.slot)

    def isModelModifiable(self):
        return self.importExport in ['public', 'to-server-only']

    def isModelReadOnly(self):
        return self.state == 'read-only' \
               or self.state == 'read-only/hidden-if-empty' \
               and not self.kind.modelValueIsEmpty(self.slot)
register(Aspect)


class ModeMixin(things.ThingMixin):
    def getModelHeaderTitle(self, object, fields, parentSlot = None):
        headerTitle = context.getVar('pageTitle', default = None)
        if not headerTitle:
            headerTitle = object.getLabelTranslated(
                    context.getVar('readLanguages'))
        return headerTitle


class ModeAbstract(ModeMixin, proxyModes.ModeAbstract):
    pass
register(ModeAbstract)


class Custom(ModeMixin, proxyModes.Custom):
    def executeModel(self, object, when, command = None, parentSlot = None):
        if self.aspects:
            for aspect in self.aspects:
                slot = object.getSlot(aspect.name, parentSlot = parentSlot)
                kind = slot.getKind()
                kind.executeModel(slot, when, command = command)
        
    def getModelLayoutInfos(self, object, fields, create, parentSlot = None):
        inForm = 0
        if self.aspects:
            aspects = []
            for readOnlyAspect in self.aspects:
                aspect = copy.copy(readOnlyAspect)
                aspects.append(aspect)
                slot = object.getSlot(aspect.name, parentSlot = parentSlot)
                aspect.slot = slot
                kind = slot.getKind()
                aspect.kind = kind
                if aspect.widget is None:
                    aspect.widget = kind.getModelWidget(slot)
                if not aspect.isModelHidden() and not aspect.isModelReadOnly():
                    inForm = 1
        else:
            aspects = []

        for aspect in aspects:
            aspect.kind.executeModel(aspect.slot, 'onDisplay')

        headerTitle = self.getModelHeaderTitle(
                object, fields, parentSlot = parentSlot)

        layout = X.array()

        if inForm:
            for slotName in object.getRequiredLayoutSlotNames(
                    fields, parentSlot = parentSlot):
                slot = object.getSlot(slotName, parentSlot = parentSlot)
                kind = slot.getKind()
                if kind.isRequiredInEditMode or kind.isExportable():
                    widget = kind.getModelWidget(slot)
                    layout += widget.getModelHiddenLayout(slot, fields)

        navigationButtons = []
        otherActionButtons = []
        actionButtons = []
        for aspect in aspects:
            if aspect.isModelHidden():
                continue
            slot = aspect.slot
            kind = aspect.kind
            widget = aspect.widget
            context.push(_level = 'getModelLayoutInfos',
                         aspect = aspect,
                         inForm = 0,
                         readOnly = 0)
            try:
                if inForm:
                    context.setVar('inForm', 1)
                    context.setVar('readOnly', aspect.isModelReadOnly())
                if not widget.hasSlotName('location') \
                       or widget.location == 'default':
                    layout += widget.getModelFieldLayout(slot, fields)
                elif widget.location == 'navigation':
                    navigationButtons.append(
                            widget.getHtmlValue(slot, fields))
                elif widget.location == 'other-action':
                    otherActionButtons.append(
                            widget.getHtmlValue(slot, fields))
                elif widget.location == 'action':
                    actionButtons.append(widget.getHtmlValue(slot, fields))
            finally:
                context.pull(_level = 'getModelLayoutInfos')
        if len(navigationButtons) + len(otherActionButtons) \
                + len(actionButtons) > 0:
            buttonsBar = X.div(_class = 'buttons-bar')
            if len(navigationButtons) > 0:
                buttonsBar += X.span(_class = 'navigation-buttons-bar')(
                        *navigationButtons)
            if len(otherActionButtons) > 0:
                buttonsBar += X.span(_class = 'other-action-buttons-bar')(
                        *otherActionButtons)
            if len(actionButtons) > 0:
                buttonsBar += X.span(_class = 'action-buttons-bar')(
                        *actionButtons)
        else:
            buttonsBar = None
        return headerTitle, layout, buttonsBar, inForm

    def getModelSlotToModifyNames(self, object, parentSlot = None):
        if self.aspects:
            slotNames = [aspect.name
                         for aspect in self.aspects
                         if aspect.isModelModifiable()]
        else:
            slotNames = []
        return slotNames

    def getModelUsersSet(self, object):
        return self.usersSet

    def submitModelFields(self, object, fields, parentSlot = None):
        object.delErrors()

        for slotName in object.getRequiredFieldSlotNames(
                fields, parentSlot = parentSlot):
            if slotName in ['thingCategory', 'thingName']:
                continue
            slot = object.getSlot(slotName, parentSlot = parentSlot)
            kind = slot.getKind()
            widget = slot.getWidget()
            if (kind.isRequiredInEditMode or kind.isExportable()) \
                   and kind.hasToSubmitField:
                try:
                    value = widget.submit(slot, fields)
                    if value is not None and \
                            type(value) != kind.pythonStorageType:
                        value = kind.convertValueFromOtherType(value)
                    if kind.isEmptyModelValue(slot, value):
                        value = None
                    kind.checkModelValue(slot, value)
                except faults.BaseFault, f:
                    self.setError(slot.getPath(), f)
                    context.setVar('again', 1)
                    context.setVar('error', 1)

                if not slot.hasValue() or value != slot.getValue():
                    slot.setValue(value)

        if self.aspects:
            for aspect in self.aspects:
                if aspect.isModelHidden():
                    continue
                slot = object.getSlot(aspect.name, parentSlot = parentSlot)
                kind = slot.getKind()
                widget = slot.getWidget()

                try:
                    value = widget.submit(slot, fields)
                    if value is not None and \
                            type(value) != kind.pythonStorageType:
                        value = kind.convertValueFromOtherType(value)
                    if kind.isEmptyModelValue(slot, value):
                        value = None
                    kind.checkModelValue(slot, value)
                except faults.BaseFault, f:
                    self.setError(slot.getPath(), f)
                    context.setVar('again', 1)
                    context.setVar('error', 1)
                slot.setValue(value)
register(Custom)


class Edit(ModeMixin, proxyModes.Edit):
    def executeModel(self, object, when, command = None, parentSlot = None):
        # Execute nothing in Edit mode.
        pass
        
    def getModelHeaderTitle(self, object, fields, parentSlot = None):
        label = object.getLabelTranslated(context.getVar('readLanguages'))
        web = context.getVar('web')
        headerTitle = N_('Editing %s - %s') % (
                self.getTranslatedObjectNameCapitalized(), label)
        return headerTitle

    def getModelLayoutInfos(self, object, fields, create, parentSlot = None):
        headerTitle = self.getModelHeaderTitle(
                object, fields, parentSlot = parentSlot)

        layout = object.getEditLayout(fields, parentSlot = parentSlot)

        web = context.getVar('web')
        buttonsBarLayout = X.div(_class = 'buttons-bar')
        actionButtonsBarLayout = X.span(_class = 'action-buttons-bar')
        buttonsBarLayout += actionButtonsBarLayout
        if create:
            actionButtonsBarLayout += X.buttonInForm('create', 'createButton')
        else:
            if web.canDeleteObject(object.id):
                actionButtonsBarLayout += X.buttonStandalone(
                        'delete', X.idUrl(object.id, 'confirmDelete'))
            actionButtonsBarLayout += X.buttonInForm('modify', 'modifyButton')

        return headerTitle, layout, buttonsBarLayout, 1

    def getModelSlotToModifyNames(self, object, parentSlot = None):
        return object.getSlotToModifyNames(parentSlot = parentSlot)

    def getModelUsersSet(self, object):
        return object.getEditModeUsersSet()

    def submitModelFields(self, object, fields, parentSlot = None):
        object.submitFields(fields)
register(Edit)


class View(ModeMixin, proxyModes.View):
    def executeModel(self, object, when, command = None, parentSlot = None):
        # Execute nothing in View mode.
        pass
        
    def getModelHeaderTitle(self, object, fields, parentSlot = None):
        headerTitle = context.getVar('pageTitle', default = None)
        if not headerTitle:
            label = object.getLabelTranslated(context.getVar('readLanguages'))
            web = context.getVar('web')
            headerTitle = '%s - %s' % (
                    self.getTranslatedObjectNameCapitalized(), label)
        return headerTitle

    def getModelLayoutInfos(self, object, fields, create, parentSlot = None):
        headerTitle = self.getModelHeaderTitle(
                object, fields, parentSlot = parentSlot)

        layout = object.getViewLayout(fields, parentSlot = parentSlot)
        web = context.getVar('web')
        buttonsBarLayout = web.getViewButtonsBarLayout(object, fields)
        return headerTitle, layout, buttonsBarLayout, 0

    def getModelUsersSet(self, object):
        return object.getViewModeUsersSet()

    def submitModelFields(self, object, fields, parentSlot = None):
        pass
register(View)


class ViewAll(ModeMixin, proxyModes.ViewAll):
    pass
register(ViewAll)

