#!/usr/bin/env python
import coral
import time

def tst(n_classes):
    filename1 = "tmp/speed_1.xmi"
    filename2 = "tmp/speed_2.xmi"
    filename_common = "tmp/speed_both.xmi"
    
    L = coral.lang.UML14
    
    m1 = L.Model()
    m2 = L.Model()
    
    for i in xrange(n_classes):
        c1 = L.Class()
        a1 = L.Attribute()
        c2 = L.Class()
        a2 = L.Attribute()
        a1.owner = c1
        a2.owner = c2
        c1.namespace = m1
        c2.namespace = m2
        a1.type = c2
        a2.type = c1
    
    prj1 = coral.Project()
    prj1.setFilename(filename1)
    prj2 = coral.Project()
    prj2.setFilename(filename2)
    
    m1.__setProject__(prj1)
    m2.__setProject__(prj2)
    
    coral.saveDocument(prj1)
    coral.saveDocument(prj2)
    
    m2.__setProject__(prj1)
    prj1.setFilename(filename_common)
    coral.saveDocument(prj1)
    
    prj1.invalidate()
    prj2.invalidate()
    
    #
    # Test load speed
    #
    def load_and_time(f):
        t_start = time.time()
        prj = coral.loadDocument(f)
        t_end = time.time()
        return prj, t_end - t_start
    prj1, t1 = load_and_time(filename1) # Loads filename2 as well
    prj2, t2 = load_and_time(filename2) # So this is almost instantaneous
    prjc, tc = load_and_time(filename_common)

    def check(p1, p2):
        for c in p1.contents()[0].ownedElement:
            assert c.feature.size() == 1
            assert c.feature[0].type
            assert c.feature[0].type.__getRootsProject__() == p2
            assert c.typedFeature.size() == 1
            assert c.typedFeature[0].__getRootsProject__() == p2
            
    check(prj1, prj2)
    check(prj2, prj1)
    check(prjc, prjc)

    prj1.invalidate()
    prj2.invalidate()
    prjc.invalidate()
    
    return t1, t2, tc

t4000_1, t4000_2, t4000_c = tst(4000)
t8000_1, t8000_2, t8000_c = tst(8000)

print 
print "TIMINGS FOR 4000 CLASSES"
print "Time to load two intermixed files", t4000_1, t4000_2
print "Time to load same data in one file", t4000_c
print 
print "TIMINGS FOR 8000 CLASSES"
print "Time to load two intermixed files", t8000_1, t8000_2
print "Time to load same data in one file", t8000_c
print

factor4000 = t4000_1 / t4000_c
factor8000 = t8000_1 / t8000_c

print "LOAD FACTORS ARE", factor4000, factor8000, " INVERSE RATIO", factor8000 / factor4000
f = factor8000 / factor4000
assert f > 0.9
assert f < 1.1
