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

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


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

from glasnost.proxy.RubricsProxy import *
from glasnost.proxy.TranslationsProxy import *

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

import WebAPI


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


class Rubric(ObjectWebMixin, Rubric):
    name_kind_widget_size = 40

    def getViewLayout(self, fields, parentSlot = None):
        layout = X.array()
        if self.contentId:
            web = getWeb(self.contentId)
            if web.canGetObject(self.contentId):
                object = web.getObject(self.contentId)
                if object.getLabel() == self.getLabel() and \
                        parentSlot and parentSlot.getLabel() == 'Root':
                    context.setVar('pageTitle',
                            getObjectLabelTranslated(self.id,
                                context.getVar('readLanguages')))
                    object.title = ''
                    context.push()
                else:
                    context.push(sectionLevel = context.getVar('sectionLevel')+1)
                layout += object.getEmbeddedViewLayout()
                context.pull()

                if web.canModifyObject(self.contentId):
                    layout += X.buttonStandalone(
                            'edit', X.idUrl(self.contentId, 'edit'))
                div = X.div(_class = 'membersSet')
        else:
            div = layout

        slot = self.getSlot('membersSet')
        if slot.getValue():
            widget = slot.getWidget()
            div += widget.getHtmlValue(slot, fields)
            if div is not layout:
                layout += div

        #layout += ObjectWebMixin.getViewLayout(
        #        self, fields, parentSlot = parentSlot)
        return layout

    def getViewLayoutSlotNames(self, fields, parentSlot = None):
        slotNames = ObjectWebMixin.getViewLayoutSlotNames(
            self, fields, parentSlot = parentSlot)
        slotNames = slotNames[:]
        userToken = context.getVar('userToken', default = '')
        useCompactLayout = context.getVar('useCompactLayout', default = 0)
        if not userToken or useCompactLayout:
            for slotName in ('contentId', 'readersSet', 'writersSet'):
                if slotName in slotNames:
                    slotNames.remove(slotName)
            if not useCompactLayout:
                slotNames.remove('name')
        return slotNames
register(Rubric)


class RubricsWeb(ObjectsWebMixin, RubricsProxy):
    def getViewOtherActionButtonsBarLayout(self, object, fields):
        layout = X.array()
        layout += ObjectsWebMixin.getViewOtherActionButtonsBarLayout(
                self, object, fields)
        if self.canModifyObject(object.id):
            roles = WebAPI.getServerRoles() # TODO: shouldn't be part of WebAPI
            form = X.form(enctype= 'multipart/form-data', method = 'post',
                          style = 'display: inline')
            form += X.asIs(_('Add:'))
            select = X.select(
                    name = 'urlsChoice', 
                    onChange = 'location.href = this.options[this.selectedIndex].value')
            form += select
            for role in WebAPI.getServerRoles():
                webRole = role.web
                if not hasattr(webRole, 'canAddObject') or \
                        not webRole.canAddObject():
                    continue
                select += X.option(
                        value = X.idUrl(object.id,
                                'addContent/%s' % role.web.serverRole))(
                        webRole.getTranslatedObjectNameCapitalized())
            if select.children:
                layout += form
        return layout

    def addContent(self, id, serverRole):
        if not self.hasObject(id):
            return pageNotFound()
        rubric = self.getObject(id)
        webRole = getWebForServerRole(serverRole)
        if webRole is None:
            return pageNotFound()
        object = webRole.newObject(None)
        object.fillWithDefaultValues()
        if object.hasSlotName('writersSet'):
            object.writersSet = rubric.writersSet
        if object.hasSlotName('readersSet'):
            object.readersSet = rubric.readersSet
        return self.addContentObject(id, serverRole, object)
    addContent.isPublicForWeb = 1

    def addContentObject(self, id, serverRole, object):
        webRole = getWebForServerRole(serverRole)
        context.push(_level = 'edit', layoutMode = 'edit')
        try:
            layout = X.array()
            leadIn = webRole.getEditLeadIn(object)
            if leadIn:
                layout += X.enclose(leadIn, _class = 'lead-in')
            if context.getVar('error'):
                layout += object.getErrorLayout()
            form = X.form(action = X.idUrl(id, 'addContentSubmit/%s' % serverRole),
                          enctype = 'multipart/form-data', method = 'post')
            layout += form
            slot = slots.Root(object)
            widget = slot.getWidget()
            form += widget.getModelPageBodyLayout(slot, None)

            buttonsBar = X.div(_class = 'buttons-bar')(
                    X.buttonInForm('create', 'createButton'))
            form += buttonsBar

            return writePageLayout(layout,
                    _('Add %s To Rubric') % \
                        webRole.getTranslatedObjectNameCapitalized())
        finally:
            context.pull(_level = 'edit')

    def addContentSubmit(self, id, serverRole, **keywords):
        if keywords is None:
            keywords = {}

        webRole = getWebForServerRole(serverRole)
        object = webRole.newObject(keywords)
        object.submitFields(keywords)
        if context.getVar('again'):
            return self.addContentObject(id, serverRole, object)

        try:
            webRole.submitAddObject(object)
        except:
            if context.getVar('debug'):
                raise
            return accessForbidden()

        rubric = self.getObject(id)
        if not rubric.membersSet:
            rubric.membersSet = []
        rubric.membersSet.append(object.id)
        self.modifyObject(rubric)

        return redirect(X.idUrl(id))
    addContentSubmit.isPublicForWeb = 1

    def file(self, serverRole):
        objectRole = getWebForServerRole(serverRole)
        if not objectRole:
            return pageNotFound()

        layout = X.array()

        form = X.form(action = X.actionUrl('fileSubmit'),
                      enctype = 'multipart/form-data', method = 'post')
        layout += form
        # TODO: use real widgets
        form += X.div(_class = 'field')(
                    X.span(_class = 'label')(X.label(_('Rubric'))),
                    X.div(_class = 'cell')(
                        X.menuIds(['rubrics'],
                        attributes = {'name': 'rubricId'})),
                )
        form += X.div(_class = 'field')(
                    X.span(_class = 'label')(X.label(_('Object'))),
                    X.div(_class = 'cell')(
                        X.menuIds([serverRole],
                        attributes = {'name': 'objectId'})),
                )
        form += X.div(_class = 'buttons-bar')(
                    X.buttonInForm(_('OK'), 'okButton'))

        return writePageLayout(layout, _('File object in rubric'))
    file.isPublicForWeb = 1

    def fileSubmit(self, **keywords):
        rubricId = keywords['rubricId']
        objectId = keywords['objectId']
        if not self.canModifyObject(rubricId):
            return faults.UserAccessDenied()
        
        rubric = self.getObject(rubricId)
        if not rubric.membersSet:
            rubric.membersSet = []
        if objectId in rubric.membersSet:
            return failure(_('Object was already in the rubric.'),
                    X.roleUrl('rubrics'))
        rubric.membersSet.append(objectId)
        self.modifyObject(rubric)
        return redirect(X.idUrl(rubricId))
    fileSubmit.isPublicForWeb = 1

