# (C) Copyright 2005 AixtraWare <http://aixtraware.de>
# Author: Joachim Schmitz <js@aixtraware.de>
#
# 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: WAeUPTables.py 440 2006-08-29 11:56:53Z joachim $

from zope.interface import implements
from Globals import InitializeClass
from Products.ZCatalog.ZCatalog import ZCatalog

from interfaces import IWAeUPTable

class AttributeHolder(object):
    pass

def dict2ob(dict):
    ob = AttributeHolder()
    for key, value in dict.items():
        setattr(ob, key, value)
        
    return ob
        

class WAeUPTable(ZCatalog):
    
    implements(IWAeUPTable)
        
    def addRecord(self, **data):
        raise NotImplementedError
    
    def deleteRecord(self, uid):
        self.uncatalog_object(uid)
    
    def modifyRecord(self, uid, **data):
        records = self.searchResults(uid=uid)
        if len(records) > 1:
            # Can not happen, but anyway...
            raise ValueError("More than one record with uid %s" % uid)
        if len(records) == 0:
            raise KeyError("No record for uid %s" % uid)
        
        record = records[0]
        record_data = {}
        for field in self.schema() + self.indexes():
            record_data[field] = getattr(record, field)
        # Add the updated data:
        record_data.update(data)
        self.catalog_object(dict2ob(record_data), uid)

class AccommodationTable(WAeUPTable):
    
    meta_type = 'WAeUP Accommodation Tool'
    
    def __init__(self):
        WAeUPTable.__init__(self, 'portal_accommodation')

    def addRecord(self, **data):
        # The uid is the same as "bed".
        uid = data['bed']
        self.catalog_object(dict2ob(data), uid=uid)
        return uid


InitializeClass(AccommodationTable)

class PinTable(WAeUPTable):
    
    meta_type = 'WAeUP Pin Tool'
    
    def __init__(self):
        WAeUPTable.__init__(self, 'portal_pins')

    def addRecord(self, **data):
        # The uid is the same as "bed".
        uid = data['bed']
        self.catalog_object(dict2ob(data), uid=uid)
        return uid


InitializeClass(PinTable)

# BBB:
AccomodationTable = AccommodationTable
