# -*- 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 Common Models"""

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


import new
import types

import context
from ObjectsCommon import AdminCommon, ObjectCommon, ObjectsCommonMixin
import slots
import tools_new as commonTools


class AdminNCardsCommon(AdminCommon):
    serverRole = 'ncards'


class NCardCommon(ObjectCommon):
    objectName = None
    class objectName_kindClass:
        _kindName = 'String'
        isRequired = 1

    objectsName = None
    class objectsName_kindClass:
        _kindName = 'String'
        isRequired = 1

    role = None
    class role_kindClass:
        _kindName = 'String'
        isRequired = 1
        isTranslatable = 0
        

    properties = None
    class properties_kindClass:
        _kindName = 'Properties'

    readersSet = None
    class readersSet_kindClass:
        _kindName = 'ReadersSet'

    serverRole = 'ncards'

    writersSet = None
    class writersSet_kindClass:
        _kindName = 'WritersSet'


    def canCache(self):
        return 1

    def getLabel(self):
        label = self.role
        if label is None:
            return ''
        return label

    def getDirectPropertyNames(self):
        if self.properties is None:
            return []
        return [property.name for property in self.properties]

    def getDirectPropertyValue(self, propertyName):
        if not self.hasDirectPropertyValue(propertyName):
            raise faults.MissingItem(propertyName)
        return self.values[propertyName]

    def getDirectPropertyValueKind(self, propertyName):
        if self.properties:
            for property in self.properties:
                if property.name == propertyName:
                    return property.kind
        return None

    def getOrderedLayoutSlotNames(self, parentSlot = None):
        slotNames = ObjectCommon.getOrderedLayoutSlotNames(
            self, parentSlot = parentSlot)
        slotNames += ['role', 'objectName', 'objectsName', 'properties',
                        'writersSet', 'readersSet']
        return slotNames

    def getPropertySlot(self, propertyName, parentSlot = None):
        propertiesSlot = self.getSlot('properties', parentSlot = parentSlot)
        return slots.Property(propertyName, parent = propertiesSlot)

    def setDirectPropertyValueKind(self, propertyName, propertyKind):
        if self.properties is None:
            self.properties = []
        else:
            for i in range(len(self.properties)):
                if self.properties[i].name == propertyName:
                    if propertyKind is None:
                        del self.properties[i]
                        return
                    else:
                        property = self.properties[i]
                        property.kind = propertyKind
                        return
        if propertyKind is not None:
            property = commonTools.newThing('other', 'Property')
            property.kind = propertyKind
            property.name = propertyName
            self.properties.append(property)

class NCardsCommonMixin(ObjectsCommonMixin):
    adminClassName = 'AdminNCards'
    newObjectNameCapitalized = N_('New Card')
    objectClassName = 'NCard'
    objectName = N_('card')
    objectNameCapitalized = N_('Card')
    objectsName = N_('cards')
    objectsNameCapitalized = N_('Cards')
    serverRole = 'ncards'


class NCardNCardCommon(ObjectCommon):
    language_kindName = None
    orderedSlotNames = None

    def getEmail(self):
        if hasattr(self, 'email'):
            return getattr(self, 'email')
        # TODO: look up an attr with kind 'Email'
        return None

    def getLabel(self):
        if hasattr(self, 'name'):
            return getattr(self, 'name')

        if self.orderedSlotNames:
            for slotName in self.orderedSlotNames:
                if slotName == 'language':
                    continue
                if not getattr(self, slotName):
                    break
                slot = self.getSlot(slotName)
                return slot.getKind().convertValueToOtherType(
                            slot.getValue(), types.StringType)
        return '%s #%s' % (self.serverRole, commonTools.extractLocalId(self.id))

    def getOrderedLayoutSlotNames(self, parentSlot = None):
        slotNames = ObjectCommon.getOrderedLayoutSlotNames(
            self, parentSlot = parentSlot)
        for slotName in self.orderedSlotNames:
            if slotName in slotNames:
                slotNames.remove(slotName)
        return slotNames + self.orderedSlotNames

class NCardsObjectsCommon:
    def getTranslatedAttribute(self, attribute):
        from glasnost.proxy.tools import getProxyForServerRole
        translationsProxy = getProxyForServerRole('translations')
        if not translationsProxy:
            return getattr(self, attribute + 'Capitalized')
        translation = translationsProxy.getTranslation(
                getattr(self, attribute + 'Capitalized'), self._nCard.id,
                'self.' + attribute, self._nCard.language,
                context.getVar('readLanguages'))
        return translation

    def getTranslatedObjectName(self):
        return self.getTranslatedAttribute('objectName').lower()

    def getTranslatedObjectNameCapitalized(self):
        return self.getTranslatedAttribute('objectName')

    def getTranslatedObjectsName(self):
        return self.getTranslatedAttribute('objectsName').lower()

    def getTranslatedObjectsNameCapitalized(self):
        return self.getTranslatedAttribute('objectsName')
    
    def getTranslatedNewObjectNameCapitalized(self):
        return _('New %s') % self.getTranslatedObjectNameCapitalized()

def getCommonMixinClass(ncard):
    # TODO: cache created classes

    objectClassDict = {
            'serverRole': ncard.role,
            '_nCard': ncard,
            'orderedSlotNames': [p.name for p in ncard.properties],
            }
    for property in ncard.properties:
        objectClassDict[property.name] = None
        objectClassDict[property.name + '_kind'] = property.kind

    objectClass = new.classobj(
            ncard.objectName,
            (NCardNCardCommon,),
            objectClassDict)
    
    objectAdminClass = new.classobj(
            ncard.objectsName + 'Admin',
            (AdminCommon,),
            {'serverRole': ncard.role})

    objectsClass = new.classobj(
            ncard.objectsName,
            (NCardsObjectsCommon, ObjectsCommonMixin,),
            { 'serverRole': ncard.role,
              'adminClass': objectAdminClass,
              'adminClassName': objectAdminClass.__name__,
              '_nCard': ncard,
              'objectClass': objectClass,
              'objectClassName': objectClass.__name__,
              'objectName': ncard.objectName.lower(),
              'objectsName': ncard.objectsName.lower(),
              'objectNameCapitalized': ncard.objectName,
              'objectsNameCapitalized': ncard.objectsName,} )

    return objectsClass

