"""
Contains classes for the creation parameters of various
resources in the repository.
"""

import ValidationInfo
#import Schema, ResourceTypes

from Ft.Server import FTSERVER_NAMESPACE
from Ft.Xml import XPath, Domlette

class CreationParams:
    """Class for resource creation parameters"""
    def __init__(self,fullTextIndex=0,vInfo = None,enforceSchema = 0,extModules = None):
        self.fullTextIndex = fullTextIndex
        self.validationInfo = vInfo or ValidationInfo.NoValidation()
        self.extModules = extModules or []
        self.enforceSchema = enforceSchema

    def getExtFunctionsAndElements(self):
        """
        Get the extension lementa and fuctions defined on these creation params
        """
        functions = {}
        elements = {}
        for mod_name in self.extModules:
            if mod_name:
                mod = __import__(mod_name,{},{},['ExtFunctions'])
                if hasattr(mod,'ExtFunctions'):
                    functions.update(mod.ExtFunctions)
                if hasattr(mod,'ExtElements'):
                    elements.update(mod.ExtElements)
        return functions,elements
           

def Serialize(cp):
    """Serialize the creation params"""
    doc = Domlette.implementation.createDocument(None, None, None)
    params = _Serialize(doc, cp)
    doc.appendChild(params)
    return doc


def Deserialize(src):
    """Create a creation params its serialized XML form."""
    dom = Domlette.NonvalidatingReader.parseString(src)
    con = XPath.Context.Context(dom, processorNss={'ftss': FTSERVER_NAMESPACE})
    return _Deserialize(con)


def _Serialize(doc,cp):
    if not cp:
        #FIXME: Where does XMLCreationParams come from
        cp = XmlCreationParams(0, ValidationInfo.NoValidation())

    params = doc.createElementNS(FTSERVER_NAMESPACE, 'ftss:CreationParams')
    params.setAttributeNS(None, 'FullTextIndex', str(cp.fullTextIndex))
    params.setAttributeNS(None, 'EnforceSchema', str(cp.enforceSchema))
    val = ValidationInfo._Serialize(doc,cp.validationInfo)
    params.appendChild(val)

    for extModule in cp.extModules:
        e = doc.createElementNS(FTSERVER_NAMESPACE,'ftss:ExtensionModule')
        e.setAttributeNS(None, 'PyImport',extModule)
        params.appendChild(e)

    return params



_creationParamsExpression = XPath.Compile('//ftss:CreationParams')
_creationParamsDocClassExpression = XPath.Compile('string(@DocumentClass)')
_creationParamsFullTextIndexExpression = XPath.Compile('@FullTextIndex')
_creationParamsValidatorExpression = XPath.Compile('ftss:Validator')
_creationParamsExtensionModulesExpression = XPath.Compile('ftss:ExtensionModule')
_creationParamsEnforceSchemaExpression = XPath.Compile('@EnforceSchema')

def _Deserialize(con):

    cp = _creationParamsExpression.evaluate(con)
    oNode = con.node

    if len(cp):

        con.node = cp[0]

        fullTextIndex = _creationParamsFullTextIndexExpression.evaluate(con)
        fullTextIndex = len(fullTextIndex) and fullTextIndex[0].value == '1'
        val = _creationParamsValidatorExpression.evaluate(con)
        if len(val):
            con.node = val[0]
            validationInfo = ValidationInfo._Deserialize(con)
            con.node = cp[0]
        else:
            validationInfo = ValidationInfo.NoValidation()

        extMods = _creationParamsExtensionModulesExpression.evaluate(con)
        extMods = map(lambda x:x.getAttributeNS(None, 'PyImport'),extMods)
        es = _creationParamsEnforceSchemaExpression.evaluate(con)
        es = len(es) and es[0].value == '1'
        creationParams = CreationParams(fullTextIndex,validationInfo,es,extMods)
    else:
        creationParams = CreationParams()

    con.node = oNode
    return creationParams

