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

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


import glasnost.common.ObjectsCommon as commonObjects

from glasnost.proxy.NCardsProxy import *

from ObjectsWeb import register, AdminMixin, ObjectWebMixin, ObjectsWebMixin
from tools import *


class AdminNCards(AdminMixin, AdminNCards):
    pass
register(AdminNCards)


def getContentPathString(contentSlot):
    contentPath = contentSlot.getPath()
    return contentPath[17:].replace("']", '').replace('.', '/')

class NCard(ObjectWebMixin, NCard):
    def makeContentTitle(self, contentSlot, contentLabel):
        return X.a(href = X.idUrl(self.id,
                'definition/%s' % getContentPathString(contentSlot)))(
                    contentLabel)
register(NCard)


class ReorderingForm(ObjectWebMixin, commonObjects.ObjectCommon):
    id_kindName = None
    language_kindName = None

    order = None
    class order_kindClass:
        _kindName = 'Sequence'
        isRequired = 1
        label = _('Order')
        class itemKind_valueClass:
            _kindName = 'String'
            stateInEditMode = 'read-only'

        def canAddItem(self, slot, fields):
            return 0
    

class NCardsWeb(ObjectsWebMixin, NCardsProxy):
    def definition(self, id, *contentPathTuple):
        if len(contentPathTuple) < 2:
            return redirect(X.idUrl(id))
        contentPath = "self.properties['%s']." % contentPathTuple[0] + \
                            '.'.join(contentPathTuple[1:])

        object = self.getObject(id)
        
        contentSlot = object.getSlotByPath(contentPath)
        contentKind = contentSlot.getKind()
        contentWidget = contentKind.getModelWidget(
                contentSlot, forceEmbedding = 1)
        layout = X.array()
        layout += contentWidget.getModelPageBodyLayout(contentSlot, None)

        buttonsBar = X.div(_class = 'buttons-bar')
        layout += buttonsBar
        navigationButtonsBar = X.span(_class = 'navigation-buttons-bar')(
                X.buttonStandalone(_('Back to object definition'), X.idUrl(id)))
        buttonsBar += navigationButtonsBar
        if self.canModifyObject(object.id):
            buttonsBar += X.span(_class = 'action-buttons-bar')(
                    X.buttonStandalone('edit',
                        X.idUrl(id,
                            'editDefinition/%s' % '/'.join(contentPathTuple))))

        return writePageLayout(
                layout, _('Definition of Card "%s"') % object.getLabel())
    definition.isPublicForWeb = 1

    def editDefinition(self, id, *contentPathTuple):
        object = self.getObject(id)

        if len(contentPathTuple) < 2:
            return redirect(X.idUrl(id))
        contentPath = "self.properties['%s']." % contentPathTuple[0] + \
                            '.'.join(contentPathTuple[1:])

        return self.editDefinitionObject(object, id, contentPath)
    editDefinition.isPublicForWeb = 1

    def editDefinitionObject(self, object, id, contentPath):
        contentSlot = object.getSlotByPath(contentPath)
        content = contentSlot.getValue()
        contentKind = contentSlot.getKind()
        contentWidget = contentKind.getModelWidget(
                contentSlot, forceEmbedding = 1)

        headerTitle = _('Editing Definition of "%s"') % object.objectsName

        context.push(_level = 'editDefinition', layoutMode = 'edit')
        try:
            layout = X.array()

            if context.getVar('error'):
                layout += object.getErrorLayout()
            form = X.form(action = X.actionUrl('submitDefinition'),
                          enctype = 'multipart/form-data', method = 'post')
            layout += form
            form += X.input(name = 'id', type = 'hidden', value = id)
            form += X.input(name = 'contentPath', type = 'hidden',
                            value = contentPath)
            form += contentWidget.getModelPageBodyLayout(contentSlot, None)

            buttonsBar = X.div(_class = 'buttons-bar')
            form += buttonsBar
            actionButtonsBar = X.span(_class = 'action-buttons-bar')
            buttonsBar += actionButtonsBar
            actionButtonsBar += X.buttonInForm('modify', 'modifyButton')
            return writePageLayout(layout, headerTitle)
        finally:
            context.pull(_level = 'editDefinition')

    def reorder(self, id):
        object = ReorderingForm()
        object.order = [x.name for x in self.getObject(id).properties]
        return self.reorderObject(id, object)
    reorder.isPublicForWeb = 1
    
    def reorderObject(self, id, object):
        layout = X.array()
        if context.getVar('error'):
            layout += object.getErrorLayout()
        form = X.form(action = X.idUrl(id, 'reorderSubmit'),
                      enctype = 'multipart/form-data', method = 'post')
        layout += form
        form += object.getEditLayout(fields = None)
        buttonsBar = X.div(_class = 'buttons-bar')
        form += buttonsBar
        actionButtonsBar = X.span(_class = 'action-buttons-bar')
        buttonsBar += actionButtonsBar
        actionButtonsBar += X.buttonStandalone('cancel', X.idUrl(id))
        actionButtonsBar += X.buttonInForm('modify', 'modifyButton')
        return writePageLayout(layout, _('Reordering fields'))

    def reorderSubmit(self, id, **keywords):
        if keywords is None:
            keywords = {}
        object = ReorderingForm()
        object.submitFields(keywords)

        if context.getVar('again'):
            return self.reorderObject(object)

        ncard = self.getObject(id)
        ncard.properties = [
                [x for x in ncard.properties if x.name == y][0] \
                    for y in object.order]
        self.modifyObject(ncard)
        return redirect(X.idUrl(id))
    reorderSubmit.isPublicForWeb = 1

    def submitDefinition(self, id, contentPath, **keywords):
        if isButtonSelected('applyButton', keywords):
            context.setVar('again', 1)
            context.setVar('hideErrors', 1)

        object = self.getObject(id)
        contentSlot = object.getSlotByPath(contentPath)
        content = contentSlot.getValue()
        contentKind = contentSlot.getKind()
        contentWidget = contentSlot.getWidget()

        contentWidget.submitEmbedded(contentSlot, keywords)

        if context.getVar('again'):
            return self.editDefinitionObject(object, id, contentPath)

        try:
            self.modifyObject(object)
        except faults.WrongVersion:
            context.setVar('again', 1)
            context.setVar('error', 1)
            object.setError('version', 1)
            return self.editDefinitionObject(object, contentPath)
        except:
            if context.getVar('debug'):
                raise
            return accessForbidden()
        return redirect(X.idUrl(id,
                'definition/%s' % getContentPathString(contentSlot)))
    submitDefinition.isPublicForWeb = 1



def getWebClass(ncard):
    proxyClass = getProxyClass(ncard)

    objectClass = new.classobj(
            proxyClass.objectClass.__name__,
            (ObjectWebMixin, proxyClass.objectClass),
            {})
    register(objectClass)

    objectAdminClass = new.classobj(
            proxyClass.adminClass.__name__,
            (AdminMixin, proxyClass.adminClass),
            {})
    register(objectAdminClass)

    objectsClass = new.classobj(
            proxyClass.__name__,
            (ObjectsWebMixin, proxyClass),
            {'adminClass': objectAdminClass,
             'objectClass': objectClass})

    return objectsClass

