from Products.CMFCore.utils import getToolByName
from Products.CMFFormController.FormAction import FormActionKey
from Products.Archetypes.Extensions.utils import installTypes
from Products.Archetypes.Extensions.utils import install_subskin
from Products.Archetypes.public import listTypes

from StringIO import StringIO

from Products.CMFDynamicViewFTI.migrate import migrateFTIs

from Products.MixedMark.config import *

def install(self):
    """Install MixedMark: Install content types, skin layer, install the
    stylesheet, set up global properties, enable the portal factory
    """

    out = StringIO()

    print >> out, "Installing MixedMark"

    # Install types
    classes = listTypes(PROJECTNAME)
    installTypes(self, out,
                 classes,
                 PROJECTNAME)
    print >> out, "Installed types"

    # Install skin
    install_subskin(self, out, product_globals)
    print >> out, "Installed skin"

    # Migrate FTI, to make sure we get the necessary infrastructure for the
    # 'display' menu to work.
    migrated = migrateFTIs(self, product=PROJECTNAME)
    print >>out, "Switched to DynamicViewFTI: %s" % ', '.join(migrated)

    # Install stylesheet
    portal_css = getToolByName(self, 'portal_css')
    portal_css.manage_addStylesheet(id = 'mixedmark.css',
                                    expression = 'python:object.getTypeInfo().getId() == "MixedMark"',
                                    media = 'all',
                                    title = 'MixedMark styles',
                                    enabled = True)

    # Enable portal_factory
    factory = getToolByName(self, 'portal_factory')
    types = factory.getFactoryTypes().keys()
    if 'MixedMark' not in types:
        types.append('MixedMark')
        factory.manage_setPortalFactoryTypes(listOfTypeIds = types)

    print >> out, "Added MixedMark to portal_factory"

    propsTool = getToolByName(self, 'portal_properties')
    siteProperties = getattr(propsTool, 'site_properties')
    navtreeProperties = getattr(propsTool, 'navtree_properties')

    # Add to default_page_types
    defaultPageTypes = list(siteProperties.getProperty('default_page_types'))
    if 'MixedMark' not in defaultPageTypes:
        defaultPageTypes.append('MixedMark')
    siteProperties.manage_changeProperties(default_page_types = defaultPageTypes)

    # Add to parentMetaTypesNotToQuery
    parentMetaTypesNotToQuery = list(navtreeProperties.getProperty('parentMetaTypesNotToQuery'))
    if 'MixedMark' not in parentMetaTypesNotToQuery:
        parentMetaTypesNotToQuery.append('MixedMark')
    navtreeProperties.manage_changeProperties(parentMetaTypesNotToQuery = parentMetaTypesNotToQuery)

    return out.getvalue()
