# (C) Copyright 2004 Nuxeo SARL <http://nuxeo.com>
# Author: Georges Racinet <gracinet@nuxeo.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# 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.
#
# $Id: utils.py 35055 2006-04-10 15:51:21Z gracinet $

from Products.CMFCore.utils import getToolByName
from Products.CPSDirectory.BaseDirectory import ConfigurationError

def _setData(self, data, **kw):
    """Set data to the entry, from a mapping."""

    # TODO : this code should be placed in parent class
    # and used by all StorageAdapter descendants
    data = self._setDataDoProcess(data, **kw)

    if not self._creation:
        # XXX Note: if we attempt to change the backing id here, we get
        # a KeyError. Unless an entry with the new backing id already
        # exists,
        # in which case, it would be overwritten...
        # An explicit test would be better.
        old_entry, b_dir = self._dir._getEntryFromBacking(self._id)
        b_dir._editEntry(data)
    else:
        dir_id = self._dir.creation_dir
        if "Student" in data.get('roles'):
            dir_id = "students"
        if not dir_id:
            raise ValueError("Creation not allowed (no backing directory)")

        dtool = getToolByName(self._dir, 'portal_directories')
        try:
            b_dir = getattr(dtool, dir_id)
        except AttributeError:
            raise ConfigurationError("No backing directory '%s'" % dir_id)

        b_dir._createEntry(data)

from Products.CPSDirectory.StackingDirectory import StackingStorageAdapter
StackingStorageAdapter._setData = _setData
