#!/usr/bin/env python

import coral
import coral.addins.UML2SMD.UML14_to_SMD01 as Uml2Smd

UML14=coral.lang.UML14

prj=coral.loadDocument("testUML14_to_SMD01.xml")

lang=None
model=None

for part in prj.contents():
    if part.oclIsKindOf(UML14.Model):
        model=part
        lang=Uml2Smd.convert(part)
        lang.__setProject__(prj)
        
assert lang
class_names=[ str(cls.name) for cls in model.__getAllParts__().select(lambda c: c.oclIsKindOf(UML14.Class) and str(c.name).find("::") == -1)]
class_names.sort()
ed_names=[ str(ed.name) for ed in lang.__getAllParts__().select(lambda c: c.oclIsKindOf(coral.lang.SMD01.ElementDefinition))]
ed_names.sort()

assert ed_names == class_names

for prop in lang.__getAllParts__().select(lambda p: p.oclIsKindOf(coral.lang.SMD01.Property)):
    if not (int(prop.multiplicity_upper) > 0 or prop.multiplicity_upper == -1):
        print "Bad multiplicity",str(elem.name)+"."+str(prop.name)
        print "upper %d "%prop.multiplicity_upper
        assert 0

    if not (int(prop.multiplicity_upper) >= int(prop.multiplicity_lower) or prop.multiplicity_upper == -1):
        print "Bad multiplicity",str(elem.name)+"."+str(prop.name)
        print prop.multiplicity_upper,">=",prop.multiplicity_lower
        assert 0

    if prop.type == "composition":
        opposite=prop.opposite
        if opposite and not opposite.multiplicity_upper == 1:
            print "Bad prop",str(opposite.owner.name)+"."+str(opposite.name)
            print "Upper mult",opposite.multiplicity_upper
            print "should be 1"
            assert 0

model_ids={}
for p in model.__getAllParts__():
    good_part=False
    if p.oclIsKindOf(UML14.Class):
        if unicode(p.name).find("::") == -1:
            good_part=True
            
    if p.oclIsKindOf(UML14.Package):
        good_part=True
    if p.oclIsKindOf(UML14.AssociationEnd):
        if p.isNavigable:
            good_part=True
    if p.oclIsKindOf(UML14.Attribute):
        good_part=True

    if good_part:
        model_ids[p.__XMIid__()]=p
    else:
        pass
        #print "Wont count", p

lang_ids={}
for ed in lang.__getAllParts__():
    print "checking id of", ed,
    assert ed.__XMIid__() in model_ids
    lang_ids[ed.__XMIid__()]=ed
    print "->", model_ids[ed.__XMIid__()]

assert len(model_ids) == len(model_ids.values())

diff_model_ids=model_ids.copy()
for id in lang_ids:
    diff_model_ids.pop(id)

for element in diff_model_ids.values():
    print "---",element
    
print len(model_ids)
print len(lang.__getAllParts__())

assert len(model_ids) == len(lang.__getAllParts__())

#TM=coral.getTransactionManager()
#TM.beginModifyCmd()
#try:
#    model.__resetAttrs__()
#finally:
#    TM.endModifyCmd()

#prj.setFilename("tmp/testUML14_to_SMD01.xml")
#coral.saveDocument(prj)
