# This file is part of the Coral project.
# Please read the copyright notice in the LICENSE file.

import string
from coral import log
logger=log.getLogger("autogen")
import coral

from coral.modeler import extension
DI = coral.lang.XMIDI20

empty_list = [ None ]

class __RendererGenerator:
    def __init__(self):

        
        self.extensions={}
        self.simpleExtensions = {}
        
    def updateExtensions(self, extRegistry):
        for entry in extRegistry.getRegisteredExtensionsByType(type="DiagramElementExt"):
            ed=extension.fromFullElementName2AbstractElementDefinition(entry[0])
            renderer = entry[1]
            if self.extensions.has_key(ed):
                if renderer not in self.extensions[ed]:
                    self.extensions[ed].append(renderer)
            else:
                self.extensions[ed]=[renderer]

        for entry in extRegistry.getRegisteredExtensionsByType(type="SimpleDiagramElementExt"):
            if self.simpleExtensions.has_key(entry[0]):
                if entry[1] not in self.simpleExtensions[entry[0]]:
                    self.simpleExtensions[entry[0]].append(entry[1])
            else:
                self.simpleExtensions[entry[0]]=[entry[1]]
            

    def getExtension(self, ge):
        assert ge
        global empty_list
        
        if ge.semanticModel:
            if ge.semanticModel.oclIsKindOf(DI.SimpleSemanticModelElement):
                typeinfo = unicode(ge.semanticModel.typeInfo)
                return self.simpleExtensions.get(typeinfo,empty_list)[0]
            elif ge.semanticModel.oclIsKindOf(DI.Uml1SemanticModelBridge):
                if ge.semanticModel.element:
                    elementdefinition = ge.semanticModel.element.__type__()
                    return self.extensions.get(elementdefinition, empty_list)[0]
                    
            else:
                logger.warn("Don't know how to handle" + str(ge) + " " + str(ge.semanticModel))
                assert 0

        return None

    def getFirstSuitableExtension(self, ge):
        """Searches recursevily through the parents of the elementdefinitions to get a suitable renderer.
        For instance a UML14::Model uses a renderer for a UML14::Package"""
        r = self.getExtension(ge)
        if r:
            return r

        lst = []
        if ge.semanticModel and ge.semanticModel.oclIsKindOf(DI.Uml1SemanticModelBridge) and ge.semanticModel.element: 
            lst = ge.semanticModel.element.__type__().getAllSuperclasses()#__superclasses__()

        for sup in lst:
            # return as soon as we find the first suitable extension
            r = self.extensions.get(sup, empty_list)[0]
            if r:
                return r

        return None

RendererGenerator = __RendererGenerator()

