# Copyright (c) 2002-2007 Infrae. All rights reserved.
# See also LICENSE.txt
# Python
from os import path
# Zope
from Globals import package_home

skinid = 'SilvaDefault'
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 default skin on Silva Root object, if doesn't have a setting yet
    setDefaultSkin(context.get_root())
    setattr(context, installed_attr, 1)

def uninstall(context):
    delattr(context, installed_attr)

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 setDefaultSkin(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})
        
