#!/usr/bin/env python

import coral
import sys
from coral.modeler.diagram.di_support import getAllLinkedProjects

ecore = coral.lang.ecore10
ecore_model = coral.loadDocument("coral/lang/ecore10/def/ecore_model.xmi").contents()[0]

smd = coral.lang.SMD01

core = coral.loadDocument("coral/core/CORE01.xmi").contents()[0]

def c(name):
    return core.elements.select(lambda x: x.name == name)[0]

def create(e):
    n = None

    if e.oclIsKindOf(ecore.EPackage):
        s = smd.Package()
        s.URInamespace = e.nsURI

    if e.oclIsKindOf(ecore.EClass):
        s = smd.ElementDefinition()
        s.isAbstract = e.interface

    if e.oclIsKindOf(ecore.EStructuralFeature):
        s = smd.Property()
        s.isBag = e.unique
        s.multiplicity_lower = e.lowerBound
        s.multiplicity_upper = e.upperBound
        if e.transient:
            s.isUnserializable = "true"
        # ignore changeable, we don't have it
        # ignore unsettable, we don't have it
        # ignore volatile, we don't have it
        # ignore many, it's not useful
        # ignore required, it's not useful
        # ignore defaultValueLiteral, we don't have it
        # ignore defaultValue, we don't have it

    if e.oclIsKindOf(ecore.EAttribute):
        s.type = "composition"
    if e.oclIsKindOf(ecore.EReference):
        if e.containment:
            s.type = "composition"
        # ignore container, it's useless
        # ignore resolveProxies, we don't have it
    assert s

    if e.oclIsKindOf(ecore.ENamedElement):
        s.name = e.name
    return s

def connect(e2s):
    for e, s in e2s.iteritems():
        if e.oclIsKindOf(ecore.EPackage):
            for child in e.eClassifiers:
                s.elements.add(e2s[child])
        if e.oclIsKindOf(ecore.EClass):
            for child in e.eStructuralFeatures:
                s.properties.add(e2s[child])
        if e.oclIsKindOf(ecore.EReference):
            if e.eOpposite:
                s.opposite = e2s[e.eOpposite]
        if e.oclIsKindOf(ecore.EStructuralFeature):
            # eAttributeType == eType
            h = { "EString": c("String"),
                  "EBoolean": c("Boolean"),
                  "EInteger": c("Integer"),
                  "EDouble": c("Double"),
                  }
            try:
                s.target = h[str(e.eType.name)]
            except KeyError:
                ed = e2s[e.eType]
                print ed
                print ed.name
                s.element_kind = e2s[e.eType]


e2s = {}
project = coral.loadDocument(sys.argv[1])
allprojects = getAllLinkedProjects([project])

for prj in allprojects:
    for root in prj.contents():
        for e in root.__getAllParts__():
            s = create(e)
            e2s[e] = s

connect(e2s)

p = coral.Project()
for e, s in e2s.iteritems():
    if e.oclIsKindOf(ecore.EPackage):
        s.__setProject__(p)
s = coral.saveDocument_str(p.contents(), "2.0")
print s
