# Copyright (c) 2002-2009 Infrae and contributors. All rights
# reserved. See also LICENSE.txt

# Python
from os import path
# Zope
from Globals import package_home
from Products.Silva.install import add_fss_directory_view

skinid = 'SilvaLegacy'
metadatasets = [('silva-layout', 'silvalayout.xml', 
                        ('Silva Root', 'Silva Publication')), 
                    ('silva-layout-vhost-root', 'silvalayoutvhostroot.xml', 
                        ('Silva Publication',)),
                ]

installed_attr = "__silva_layout_installed__"

def is_installed(context):
    return hasattr(context, installed_attr)

def install(context):
    # configure metadata
    configureMetadata(context)
    # set initial skin on Silva Root object, if doesn't have a setting yet
    setInitialSkin(context.get_root())
    setattr(context, installed_attr, 1)

    root = context
    add_fss_directory_view(root.service_views,
                           'SilvaLayout', __file__, 'views')
    reg = root.service_view_registry

    # define metadata sets for sample versioned content
    root.service_metadata.addTypesMapping(
        ('Silva Layout Configuration', ), ('silva-content', 'silva-extra'))
    root.service_metadata.initializeMetadata()
    
    # edit
    reg.register('edit', 'Silva Layout Configuration',
                 ['edit', 'Asset', 'LayoutConfiguration'])
    # public
    reg.register('public', 'Silva Layout Configuration',
                 ['public', 'LayoutConfiguration'])
    # add
    reg.register('add', 'Silva Layout Configuration',
                 ['add', 'LayoutConfiguration'])

def uninstall(context):
    resetMetadata(context, ['silva-layout', 'silva-layout-vhost-root'])
    delattr(context, installed_attr)

    root = context
    reg = root.service_view_registry
    reg.unregister('edit', 'LayoutConfiguration')
    reg.unregister('public', 'LayoutConfiguration')
    reg.unregister('add', 'LayoutConfiguration')
    if hasattr(root.service_views, 'SilvaLayout'):
        root.service_views.manage_delObjects(['SilvaLayout'])    
    
def configureMetadata(context):
    product = package_home(globals())
    schema = path.join(product, 'schema')
    
    for setid, xmlfilename, types in metadatasets:
        collection = context.service_metadata.getCollection()
        if not setid in collection.objectIds():
            xmlfile = path.join(schema, xmlfilename)
            definition = open(xmlfile, 'r')        
            collection.importSet(definition)

        context.service_metadata.addTypesMapping(types, (setid, ))
    context.service_metadata.initializeMetadata()
    
def setInitialSkin(silvaroot):
    setid = 'silva-layout'
    metadataservice = silvaroot.service_metadata
    currentskin = metadataservice.getMetadataValue(silvaroot, setid, 'skin')
    if not currentskin:
        binding = metadataservice.getMetadata(silvaroot)
        binding.setValues(setid, {'skin': skinid})
        
def resetMetadata(root, metadatasets):
    """Removes metadata sets from the metadata mapping."""
    mapping = root.service_metadata.getTypeMapping()
    default = ''
    # Get all content types that have a metadata mapping
    content_types =  [item.id for item in mapping.getTypeMappings()]
    tm = []
    # Remove the metadata sets for each content type
    for content_type in content_types:
        chain = mapping.getChainFor(content_type)
        sets = [set.strip() for set in chain.split(',')]
        sets_to_remove = []
        for set in sets:
            if set in metadatasets:
                sets_to_remove.append(set)
        for set in sets_to_remove:
            sets.remove(set)
        map = {'type':content_type,
               'chain':', '.join(sets)}
        tm.append(map)
    mapping.editMappings(default, tm)

    # Remove the metadata set specifications
    root.service_metadata.collection.manage_delObjects(metadatasets)
