"""\
This file is an installation script for CMFForum (ZPT skins).  It's meant
to be used as an External Method.  To use, add an external method to the
root of the CMF Site that you want ZPT skins registered in with the
configuration:

 id: install_forum
 title: Install Forum Product *optional*
 module name: CMFForum.Install
 function name: install

Then go to the management screen for the newly added external method
and click the 'Test' tab.  The install function will execute and give
information about the steps it took to register and install the
ZPT skins into the CMF Site instance. 
"""

from Products.CMFCore.TypesTool import ContentFactoryMetadata
from Products.CMFCore.DirectoryView import addDirectoryViews
from Products.CMFCore.utils import getToolByName
from Products.ExternalMethod import ExternalMethod

from Acquisition import aq_base
from cStringIO import StringIO
import string
import string 

from Acquisition import Implicit
import Persistence

from Products.CMFForum import cmfforum_globals, Forum, Post

__version__='0.1'

def install_SubSkin(self, outStream, skinFolder):
    """ Installs a subskin, should be just 1 folder.
    """
    skinstool=getToolByName(self, 'portal_skins')
    for skin in skinstool.getSkinSelections():
        path = skinstool.getSkinPath(skin)
        path = map( string.strip, string.split( path,',' ) )
        if not skinFolder in path:
            try:
                path.insert( path.index( 'custom')+1, skinFolder )
            except ValueError:
                path.append(skinFolder)
            path = string.join( path, ', ' )
            skinstool.addSkinSelection( skin, path )
            outStream.write('CMFForum subskin successfully installed into %s.\n' % skin)    
        else:
            outStream.write('CMFForum subskin was already installed into %s.\n' % skin)    

def install_ForumSkins(self, out):
    """
        Add a new skin, 'Plone', copying 'ZPT', if it exists, and then
        add our directories only to it.
    """

    skinstool = getToolByName(self, 'portal_skins')

    try:
        install_SubSkin(self, out, 'zpt_forum')
        out.write('CMFForum subskin successfully installed.\n')
    except:
        out.write('CMFForum subskin failed to install.\n')

    try:  
        addDirectoryViews( skinstool, 'skins', cmfforum_globals )
        out.write( "Added CMFForum directory views to portal_skins.\n" )
    except:
        out.write( 'Unable to add CMFForum directory view to portal_skins.\n')

def install(self):
    """ Register the Forum Skins with portal_skins and friends """
    skinstool = getToolByName(self, 'portal_skins')
    wf_tool = getToolByName(self, 'portal_workflow')

    out = StringIO()
    out.write( 'CMFForum installation tool v' + str(__version__) + '.\n')

    install_ForumSkins(self, out)

    # Register with the typestool manually instead of with manage_addTypeInformation
    # as the classes were not registered with utils.ContentInit in __init__.py
    types_tool = getToolByName(self, 'portal_types')
    for t in (Forum.factory_type_information,Post.factory_type_information):
        if t['id'] not in types_tool.objectIds():
            cfm = apply(ContentFactoryMetadata, (), t)
            types_tool._setObject(t['id'], cfm)
            out.write('Registered %s with the types tool\n' % t['id'])
        else:
            out.write('Skipping "%s" - already in types tool\n' % t['id'])

    # Remove workflows for Forum and Post
    wf_tool.setChainForPortalTypes( ('Forum','Post'), [])
    out.write('Removed workflow for Forum and Post')
            
    return out.getvalue()

def install_discussions(self):
    """ Replace default DiscussionTool from CMF by a CMFForum-based one """

    out = StringIO()
    out.write( 'CMFForum installation tool v' + str(__version__) + '.\n')

    install_SubSkin(self, out, 'zpt_forum/discussion')

    out.write( '* Replacing Default CMF DiscussionTool by CMFForums one.')
    self.manage_delObjects( 'portal_discussion' )
    addPloneTool=self.manage_addProduct['CMFForum'].manage_addTool
    addPloneTool('CMFForum Discussion Tool', None)
    out.write( 'Done.')

    return out.getvalue()
