##############################################################################
# Copyright (c) 2004-2005 Black Rock City, LLC
# Copyright (c) 2004-2005 ObjectRealms, LLC
# Copyright (c) 2006 Amaze Internet Services
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################

"""
$Id: $
"""
from StringIO import StringIO

from borg.localrole.utils import setup_localrole_plugin
from Products.Archetypes.Extensions.utils import installTypes, install_subskin
from Products.Archetypes.public import listTypes
from Products.TeamSpace import *
from Products.CMFCore.utils import getToolByName, manage_addTool
from Products.CMFCore.permissions import ManagePortal
from OFS.ObjectManager import BadRequestException

from Products.TeamSpace.config import PROJECTNAME
from Products.TeamSpace.Extensions.addMemberTeamReferences \
     import addMemberTeamReferences

CONFIGLET_ID = 'TeamSpacePrefs'

def installUIDIndex(self, out):
    cat = getToolByName(self, 'portal_catalog')
    if 'UID' not in cat.indexes():
        cat.addIndex('UID', 'FieldIndex')
        print >> out, 'Installed UID index in portal_catalog'


def setupConfiglet(portal):
    portalConf = getToolByName(portal, 'portal_controlpanel')
    portalConf.unregisterConfiglet(CONFIGLET_ID)
    try:
        portalConf.registerConfiglet(
                id=CONFIGLET_ID,
                name='TeamSpace teams',
                action='string:${portal_url}/portal_teams/', 
                permission=ManagePortal,
                category='Products',
                appId=PROJECTNAME,
                imageUrl='teams_tool.png')
    except KeyError:
        pass

def setupPortalFactory(portal, out):
    # enable portal_factory for given types
    factory_tool = getToolByName(portal,'portal_factory')
    old_factory_types = factory_tool.getFactoryTypes().keys()
    factory_types = list(old_factory_types)
    these_types = [x['portal_type'] for x in listTypes(PROJECTNAME)]
    for x in these_types:
        if x not in factory_types:
            factory_types.append(x)

    factory_tool.manage_setPortalFactoryTypes(listOfTypeIds=factory_types)
    print >> out, "Changed portal_factory types from %s to %s." % (old_factory_types, factory_types)

def install( self ):
    out = StringIO()

    print >> out, "Installing Dependencies"

    installer = getToolByName(self, 'portal_quickinstaller')

    dependencies = ('PortalTransforms','Archetypes', 'PlonePAS')
    for product in dependencies:
        if not installer.isProductInstalled(product):
            installer.installProduct(product)

    print >> out, 'Installed Types' 
    installTypes( self, out, listTypes(PKG_NAME), PKG_NAME)

    print >> out, 'Installed Skins' 
    install_subskin( self, out, GLOBALS )

    installUIDIndex(self, out)

    try:
        print >> out, 'Added Teams Tool'
        m = self.manage_addProduct[PKG_NAME]
        manage_addTool(m, 'Teams Tool')
    except BadRequestException: # already exists
        pass

    print >> out, 'Install Membership Workflow'
    installWorkflow(self)

    print >> out, 'Register with control panel'
    setupConfiglet(self)

    print >> out, 'Install borg.localrole PAS plug-in'
    result = setup_localrole_plugin(self)
    print >> out, result

    print >> out, "Registered Action Provider"
    portal_teams = getToolByName(self, 'portal_teams')
    portal_controlpanel = getToolByName(self, 'portal_controlpanel')
    portal_properties = getToolByName(self, 'portal_properties')
    portal_actions = getToolByName(self, 'portal_actions')
    portal_actions.addActionProvider( portal_teams.getId() )
    
    # dont allow tool listed as content in navtree
    ntp = getToolByName(self, 'portal_properties').navtree_properties
    prop_name = 'metaTypesNotToList'
    blacklist = ntp.getProperty(prop_name)
    if blacklist is not None:
        blacklist = list(blacklist)
        if not 'TeamsTool' in blacklist:
            blacklist.append('TeamsTool')
        ntp.manage_changeProperties(**{prop_name:tuple(blacklist)})

    if not getattr(portal_teams, '_addedMemberTeamReferences', False):
        addMemberTeamReferences(self)
        print >> out, 'Added required MemberTeamRelation references'

    setupPortalFactory(self, out)

    return out.getvalue()

def installWorkflow(self):
    from Products.TeamSpace.workflows import membership
    id = 'team_membership_workflow'
    membership.create_team_membership_workflow(id)

    wf_tool = getToolByName(self, 'portal_workflow')
    if not id in wf_tool.objectIds():
        wf_tool.manage_addWorkflow(
           'team_membership_workflow (Team Membership Workflow [Simple Approval])',
           'team_membership_workflow'
            )
        
    wf_tool.setChainForPortalTypes(('Team Membership',), id)
    return "Wow"
