#!/usr/bin/env python
import coral
from coral.addins.constraint.evaluate import GraphicalScriptConstraintEvaluator, QueryScriptConstraintEvaluator

prj = coral.loadDocument("testEvaluate.xml")
query = None
target = None

for elem in prj.contents():
    if elem.oclIsKindOf(coral.lang.UML14.Model):
        if elem.name == "Query":
            query = elem
        if elem.name == "Target":
            target = elem

assert query
assert target

try:
    f = open('script.py', 'r')
    script = f.read()
    f.close()
except:
    assert 0, "Error while reading file script.py"
    
try:
    gsc = GraphicalScriptConstraintEvaluator(query.ownedElement, script)
except SyntaxError:
    assert 0,"Good script didn't compile:-("
else:
    print "Good script OK!"
    
gsc.searchApply(target)

try:
    f = open('badScript.py', 'r')
    script = f.read()
    f.close()
except:
    assert 0, "Error while reading file badScript.py"

try:
    gsc = GraphicalScriptConstraintEvaluator(query.ownedElement, script)
except SyntaxError:
    print "Bad script OK!"
except:
    assert 0

try:
    f = open('badScript2.py', 'r')
    script = f.read()
    f.close()
except:
    assert 0, "Error while reading file badScript2.py"

try:
    gsc = GraphicalScriptConstraintEvaluator(query.ownedElement, script)
except SyntaxError:
    assert 0

try:
    gsc.searchApply(target)
except:
    print "badScript2.py OK:-)"
else:
    assert 0

#################################################
prj2 = coral.loadDocument("testQueryScriptConstraint.xml")
target = None


for elem in prj2.contents():
    if elem.oclIsKindOf(coral.lang.UML14.Model):
        target = elem
        
for elem in prj2.contents():
    for part in elem.__getAllParts__().select(lambda p:p.oclIsKindOf(coral.lang.CONSTRAINT10.QueryScriptConstraint)):
        qsc = QueryScriptConstraintEvaluator(part)
        qsc.searchApply(target)
