#-*- mode: python; mode: fold -*-
# $Id: exportimport.py 1221 2007-01-07 10:47:01Z henrik $
"""WAeUP Tool XML Adapter.

An XML adapter tells the GenericSetup machinery howto im- / export persistent
configuration that is relative to a specific CMF component such as our WAeUP
Tool.

GenericSetup uses the Zope3 interfaces and components machinery to find the
right XML adapter for the right object. This is why we flagged our waeup tool
with the `implements(IWAeUPTool)` class attribute and made an adapter
association in the `configure.zcml` file.
"""
import csv,re

# Zope3 component architecture
from zope.app import zapi
from zope.component import adapts
from zope.interface import implements

# Standard GenericSetup base classes and functions
from Products.GenericSetup.utils import exportObjects
from Products.GenericSetup.utils import importObjects
from Products.GenericSetup.utils import XMLAdapterBase
from Products.GenericSetup.utils import PropertyManagerHelpers

from Products.CMFCore.utils import getToolByName

# GenericSetup multi adapts a class that implement IWAeUP and a particular
# ISetupEnvironment to and IBody (piece of XML configuration).
from Products.GenericSetup.interfaces import IBody
from Products.GenericSetup.interfaces import ISetupEnviron
from Products.WAeUP_SRP.interfaces import IWAeUPTool
import Globals
p_home = Globals.package_home(globals())
i_home = Globals.INSTANCE_HOME

TOOL = 'portal_waeup'
NAME = 'waeup'

def importWAeUPTable(obj, parent_path, context, name):
    """ Import subobjects recursively.
    """
    importer = zapi.queryMultiAdapter((obj, context), IBody)

    path = '%s%s' % (parent_path, obj.getId().replace(' ', '_'))
    __traceback_info__ = path
    if importer:
        path = '%s%s' % (parent_path, name)
        filename = '%s%s' % (path, importer.suffix)
        body = context.readDataFile(filename)
        if body is not None:
            importer.filename = filename # for error reporting
            importer.body = body

    if getattr(obj, 'objectValues', False):
        for sub in obj.objectValues():
            importObjects(sub, path+'/', context)

def exportWAeUP(context):
    """Export our WAeUP tool configuration
    """
    site = context.getSite()
    tool = getattr(context,"campus",None)
    if tool is None:
        logger = context.getLogger(NAME)
        logger.info("Nothing to export.")
        return
    exportObjects(tool, '', context)

def importWAeUP(context):
    """Import WAeUP tool configuration
    """
    site = context.getSite()
    pm = site.portal_membership
    campus = getattr(site.portal_url.getPortalObject(),'campus',None)
    if campus is not None:
        academics = getattr(campus,'academics',None)
        students = getattr(campus,'students',None)
        accommodation = getattr(campus,'accommodation',None)
        if academics is not None:
            academics.manage_setLocalGroupRoles(groupid='role:Authenticated',
                                         roles=('SectionReader',))
        if students is not None:
            students.manage_setLocalGroupRoles(groupid = 'ClearanceOfficers',
                                              roles=('SectionReader',))
            students.manage_setLocalGroupRoles(groupid='MemberAdmins',
                                         roles=('SectionOfficer',))                                         
            students.manage_setLocalGroupRoles(groupid = 'role:Student',
                                              roles=('SectionReader',))
        if accommodation is not None:
            accommodation.manage_setLocalGroupRoles(groupid='role:Student',
                                         roles=('SectionReader',))
    members = getattr(site.portal_directories,'members')
    if members is not None:
        members.manage_setLocalGroupRoles(groupid='MemberAdmins',
                                         roles=('SectionOfficer',))

##    pm.setLocalGroupRoles(campus.academics,['role:Authenticated',
##                                           ],'SectionReader')
    importWAeUPTable(site.portal_accommodation, '', context,'accommodation')
    importWAeUPTable(site.courses_catalog, '', context,'courses_catalog')
    importWAeUPTable(site.payments_catalog, '', context,'payments_catalog')
    importWAeUPTable(site.portal_pins, '', context,'pins')
    importWAeUPTable(site.portal_pumeresults, '', context,'pumeresults')
    importWAeUPTable(site.returning_import, '', context,'returning_import')
    importWAeUPTable(site.results_import, '', context,'results_import')
    importWAeUPTable(site.students_catalog, '', context,'students_catalog')

from Products.CPSCore.exportimport.catalog import CatalogToolXMLAdapter
#from Products.GenericSetup.ZCatalog.exportimport import ZCatalogXMLAdapter

from interfaces import IWAeUPTable

class WAeUPTableXMLAdapter(CatalogToolXMLAdapter):
#class WAeUPTableXMLAdapter(ZCatalogXMLAdapter):
    __used_for__ = IWAeUPTable
    _LOGGER_ID = 'waeup_table'

##    def _importNode(self, node):
##        """Import the object from the DOM node.
##        """
##        if self.environ.shouldPurge():
##            self._purgeProperties()
##            self._purgeObjects()
##            self._purgeIndexes()
##            self._purgeColumns()
##
##        self._logger.info('Catalog imported.')
# This the XMLAdapter itself. It encodes the im- / export logic that is specific
# to our tool. `im- / exportObjects` functions will find it thanks to the zope
# components machinery and the associations made in the configure.zcml file.

##class WAeUPXMLAdapter(XMLAdapterBase, PropertyManagerHelpers):
##    """XML importer and exporter for the WAeUP tool.
##
##    Hence this XMLAdapter is really simple. To get more complete examples of
##    what XMLAdapters are meant to do, please have a look at the
##    CPSSkins.exportimport.py or CPSDirectory.exportimport.py files, for
##    instance.
##    """
##
##    adapts(IWAeUPTool, ISetupEnviron)
##    implements(IBody)
##
##    _LOGGER_ID = NAME
##    name = NAME
##
##    def _exportNode(self):
##        """Export the object as a DOM node.
##        """
##        node = self._getObjectNode('object')
##        node.appendChild(self._extractProperties())
##        self._logger.info("WAeUP tool exported.")
##        return node
##
##    def _importNode(self, node):
##        """Import the object from the DOM node.
##        """
##        if self.environ.shouldPurge():
##            self._purgeProperties()
##        self._initProperties(node)
##        self._logger.info("WAeUP tool imported.")
##
