from Products.CMFCore.DirectoryView import addDirectoryViews
from Products.CMFCore.utils import getToolByName
from cStringIO import StringIO
from Products import TTWType
import string


def install(self):
    """ install the skins """
    out=StringIO()

    out=addSkins(self,out)
    #out=addNavigation(self,out)
    #out=addValidation(self,out)
    return out.getvalue()

def addSkins(self,out):
    """ add skins """

    skins_tool = getToolByName(self, 'portal_skins') 
    if 'ttwtype' not in skins_tool.objectIds():
	addDirectoryViews(skins_tool, 'skins', TTWType.ttwtype_globals)
	out.write("Added ttwtype skin directory view to portal_skins\n")

    skins = skins_tool.getSkinSelections()
    for skin in skins:
        path = skins_tool.getSkinPath(skin)
        path = map(string.strip, string.split(path,','))
        if 'ttwtype' not in path:
            try: path.insert(path.index('content'), 'ttwtype')
            except ValueError:
                path.append('ttwtype')
                 
            path = string.join(path, ', ')
            # addSkinSelection will replace existing skins as well.
            skins_tool.addSkinSelection(skin, path)
            out.write("Added 'ttwtype' to %s skin\n" % skin)
        else:
            out.write("Skipping %s skin, 'ttwtype' is already set up\n" % (
                skin))
    return out

def addNavigation(self,out):
    """ add to the navigation tool 
        NOT USESD because we use the FormController
    """
    try:
	nav_tool = getToolByName(self, 'portal_navigation')
    except AttributeError:
	out.write('navigation tool not found. not installing\n')
	return out
    
    # add the transitions
    nav_tool.addTransitionFor(
	    'default',
	    'ttw_content_edit',
	    'failure',
	    'portal_form/ttw_edit_form')

    nav_tool.addTransitionFor(
	    'default',
	    'ttw_content_edit',
	    'success',
	    'action:view')

    nav_tool.addTransitionFor(
	    'default',
	    'ttw_edit_form',
	    'success',
	    'script:ttw_content_edit')

    nav_tool.addTransitionFor(
	    'default',
	    'ttw_edit_form',
	    'failure',
	    'portal_form/ttw_edit_form')

    out.write("added transitions to navigation tool\n")
    return out

def addValidation(self,out):
    """ add validation to the form tool
        NOT USESD because we use the FormController
     """
    try:
	form_tool = getToolByName(self, 'portal_form')
    except AttributeError:
	out.write('form tool not found. not installing validation\n')
	return out

    form_tool.setValidators("ttw_edit_form", 
	['validate_id', 'validate_ttw_edit'])

    out.write("added validation to form tool\n")
    return out

