#-*- mode: python; mode: fold -*-
# (C) Copyright 2005 The WAeUP group  <http://www.waeup.org>
# 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: WAeUPTool.py 197 2006-02-08 12:47:31Z joachim $
"""The WAeUPTool.
"""

from zLOG import LOG, DEBUG
from Globals import InitializeClass, HTMLFile
from AccessControl import ClassSecurityInfo
from OFS.Folder import Folder

from Products.CPSInstaller.CPSInstaller import CPSInstaller
from Products.CMFCore.PortalFolder import PortalFolder
from Products.CMFCore.permissions import View, ManagePortal
from Products.CMFCore.utils import UniqueObject

class WAeUPTool(UniqueObject,PortalFolder):
    """WAeUP tool"""

    id = 'portal_WAeUP'
    meta_type = 'WAeUP Tool'

    security = ClassSecurityInfo()
    manage_options = (#ActionProviderBase.manage_options +
                      PortalFolder.manage_options[:1] +
                      PortalFolder.manage_options[2:])

    _actions = ()


    #
    # ZMI
    #
    _properties = (
        {'id': 'title', 'type': 'string', 'mode': 'w', 
         'label': 'Title'},
        {'id': 'uni_id', 'type': 'string', 'mode': 'w', 
         'label': 'University ID'},
        {'id': 'uni_name', 'type': 'string', 'mode': 'w', 
         'label': 'University Name'},
    )
    title = ''
    def __init__(self,uni_id,uni_name):
        self.manage_changeProperties(uni_id = uni_id,
                                     uni_name = uni_name,
                                     )
        PortalFolder.__init__(self, self.id)


    def verifyFaculties(self, academics): ###(
        """install Universityspecific Faculies with Departments"""
        faculties = [
##                     {'id': 'agri', ###(
##                      'Title': 'Agriculture',
##                      'departments': [
##                                     { 'id': 'dep1', ###(
##                                       'Title': 'One',
##                                     },
##                                     ],
##                      },###)
                      { 'id': 'science',
                      'Title': 'Science',
                      'departments': [
                                     { 'id': 'bio', ###(
                                       'Title': 'Biochemistry',
                                     },
                                     { 'id': 'bot',
                                       'Title': 'Botany',
                                     },
                                     { 'id': 'che',
                                       'Title': 'Chemistry',
                                     },
                                     { 'id': 'com',
                                       'Title': 'Computer Science',
                                     },
                                     { 'id': 'geo',
                                       'Title': 'Geologie',
                                     },
                                     { 'id': 'mat',
                                       'Title': 'Mathematics',
                                     },
                                     { 'id': 'mic',
                                       'Title': 'Microbiology',
                                     },
                                     { 'id': 'opt',
                                       'Title': 'Optometry',
                                     },
                                     { 'id': 'phy',
                                       'Title': 'Physics',
                                     },
                                     { 'id': 'zoo',
                                       'Title': 'Zoology',
                                     },
                                     ],
                      },###)
                     ]###)
        #self.log('Verifying Faculties in %s' % academics.absolute_url(relative=1))
        for faculty in faculties:
            fid = faculty['id']
            f = getattr(academics,fid,None)
            #self.log('Checking Faculty %(id)s = %(Title)s' % faculty)
            if f is None:
                #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
                academics.invokeFactory('Faculty', fid)
                f = getattr(academics,fid)
                f.getContent().edit(mapping=faculty)
            for department in faculty['departments']:
                #self.log('Checking Department %(id)s = %(Title)s' % department)
                did = department['id']
                d = getattr(f,did,None)
                if d is None:
                    #self.log('Creating Department %(id)s = %(Title)s' % department)
                    f.invokeFactory('Department', did)
                    d = getattr(f,did)
                    d.getContent().edit(mapping=department)
    ###)

InitializeClass(WAeUPTool)

def verifyPortlets(portal, portlets=(), object=None): ###(
    """Verify the existence of given portet in the object's portlet
    container. If not found, a portlet is instantiated.
    Existing portlets are not affected.
    'portlets' is a tuple with the dictionaries given by the export tab
    as entries.
    The default object is the portal itself.
    return the list a new portlet ids.
    """
    #self.log('Verifying portlets on %s' % object.absolute_url(relative=1))
    #portlet_container = CPSInstaller.getPortletContainer(object, create=1)
    idpc = portal.portal_cpsportlets.getPortletContainerId()
    if not hasattr(object, idpc):
##            self.log("   Creating %s/%s" %
##                (object.absolute_url(relative=1), idpc))
        object.manage_addProduct['CPSPortlets'].addPortletsContainer()
    portlet_container = getattr(object, idpc, None)
    ttool = portal.portal_types
    returned = []
    for new_portlet in portlets:
        existing_portlets = portlet_container.listPortlets()
        updated = 0
        # Check if the portlet needs an update
        identifier = new_portlet.get('identifier')
        if identifier:
            for portlet in existing_portlets:
                if identifier == portlet.identifier:
                    #portal.log(" Update of portlet: %s" % portlet)
                    portlet.edit(**new_portlet)
                    portlet_id = portlet.getId()
                    updated = 1
                    continue
        slot = new_portlet.get('slot')
        if slot:
            for portlet in existing_portlets:
                if slot == portlet.slot:
                    #portal.log(" Update of portlet: %s" % portlet)
                    portlet.edit(**new_portlet)
                    portlet_id = portlet.getId()
                    updated = 1
                    continue
                
        if not updated:
            #portal.log("   Creation of portlet: %s" % new_portlet)
            portlet_id = portal.portal_cpsportlets.createPortlet(
            ptype_id=new_portlet['type'],
            context=object,
            **new_portlet)
        if portlet_id not in returned:
            returned.append(portlet_id)
    return returned
    ###)

addWAeUPToolForm = HTMLFile('zmi/manage_addWAeUPUniversity',
                                                globals())

def addWAeUPTool(container, id,
                             title='WAeUP University',
                             description='',
                             langs_list=None,
                             manager_id='manager',
                             manager_sn='CPS',
                             manager_givenName='Manager',
                             manager_email='',
                             manager_password='',
                             manager_password_confirmation='',
                             REQUEST=None):
    """Add WAeUPTool"""

    _log = []
    def pr(bla, zlog=1, _log=_log):
        if bla == 'flush':
            return '<br/>\n'.join(_log)
        _log.append(bla)
        if (bla and zlog):
            LOG('addWAeUPUniversity:', INFO, bla)

    uni_id = id.strip()
    uni_name = title.strip()
    description = description.strip()
    manager_id = manager_id.strip()

##    if not id:
##        raise ValueError, "You have to provide an id for the portal!"
##    if not manager_id:
##        raise ValueError, "You have to provide an id for the CPS Administrator!"
##    if not manager_email:
##        raise ValueError, "You have to provide an email address for the CPS Administrator!"
##    if not manager_password:
##        raise ValueError, "You have to provide CPS Administrator password!"
##    if manager_password != manager_password_confirmation:
##        raise ValueError, "Password confirmation does not match password!"

    email_from_name = ('%s %s' % (manager_givenName, manager_sn)).strip()
    wt = WAeUPTool(uni_id,uni_name)
    id = wt.getId()
    container._setObject(id, wt)
    sections = getattr(container,'sections')
    workspaces = getattr(container,'workspaces') 
    sections.invokeFactory('University',uni_id)
    uni = getattr(sections,uni_id)
    uni.getContent().edit(title=uni_name)
    uni.invokeFactory('StudentsFolder','students')
    students = getattr(uni,'students').getContent()
    students.edit(mapping={'Title':'Students'})
##    uni.folder_localrole_add(member_ids=('group:Students',),
##                                            member_role='SectionReviewer',
##                                            )
##        uni.content_create(type_name='AcademicsFolder',title='academics')
##        sections.uni.folder_localrole_add(member_ids=('group:StudentManager',),
##                                            member_role='SectionManager',
##                                            )
##        uni.students.manage_setLocalGroupRoles(groupid = 'Students',roles=('Contributor',))
    uni.invokeFactory('AcademicsFolder','academics', title='Academics')
    academics = getattr(uni,'academics').getContent()
    academics.edit(mapping={'Title':'Academics'})
    uni.invokeFactory('AccoFolder','accommodation', title='Accommodation')
    accommodation = getattr(uni,'accommodation').getContent()
    accommodation.edit(mapping={'Title':'Accommodation'})
    academics = getattr(uni,'academics',None)
    if academics is None:
        uni.invokeFactory('AcademicsFolder','academics')
        academics = getattr(uni,'academics')
        academics.getContent().edit(mapping={'Title':'Academics'})
    wt.verifyFaculties(academics)
    if not hasattr(uni,'accommodation'):
        uni.invokeFactory('AccoFolder','accommodation')
        accommodation = getattr(uni,'accommodation').getContent()
        accommodation.edit(mapping={'Title':'Accommodation'})
    #uni.manage_setLocalGroupRoles(groupid = 'role:Anonymous',roles=('SectionReader',))
    # portlets ###(
    #
    portlets = (
              {#'identifier': 'waeup_breadcrumbs',
              'type': 'Breadcrumbs Portlet',
              'slot': 'waeup_breadcrumbs',
              'first_item': 0,
              'display_site_root': 0,
              'Title': 'waeup_breadcrumbs',
              'display': 'horizontal_trail',
              'display_hidden_folders': 0,
              'order': 0,
              },
              {#'identifier': 'waeup_main_tab_actions',
              'type': 'Actions Portlet',
              'slot': 'main_tabs',
              'order': 0,
              'categories': ['main_tabs',],
              'Title': 'waep_main_tab_actions',
              },
              {#'identifier': 'waeup_object_actions',
              'type': 'Actions Portlet',
              'slot': 'waeup_object_actions',
              'order': 0,
              'categories': ['object',],
              'Title': 'waep_manager_actions',
              },
              {#'identifier': 'waeup_left_top',
              'type': 'Custom Portlet',
              'slot': 'left_top',
              'order': 0,
              'render_method': 'portlet_session_info',
              'Title': 'Session Info',
              },
            )
    #verifyPortletContainer(uni)
    verifyPortlets(container,portlets,uni)

    ###)
    if REQUEST is not None:
        url = container.absolute_url()
        REQUEST.RESPONSE.redirect('%s/manage_main' % url)

