#!/usr/bin/env python
import coral
import coral.modeler
import coral.modeler.modeler

TM = coral.getTransactionManager()

#mw = coral.modeler.modeler.ModelerWindow()
#mw.processEvents()

L = coral.lang.CoralEx10

def testFolder(folder):
    print "testing ",folder
    assert len(folder.__type__().getOperations())>0
    for entry in folder.contents:
        assert len(entry.__type__().getOperations())>0
        if entry.oclIsKindOf(L.FileSystem.Folder):
            testFolder(entry)

def cmpEntry(file1, file2):
    return file1.name == file2.name

def getEntry(folder, entry):
    for f in folder.contents:
        if cmpEntry(f, entry):
            if f.oclIsKindOf(L.FileSystem.File) and entry.oclIsKindOf(L.FileSystem.File):
                print "Comparing file contents of",f.name,"and",entry.name
                assert f.text==entry.text
            return f
    return None

def cmpFolders(folder1, folder2):
    print folder1.name,"==",folder2.name
    assert folder1.name == folder2.name
    assert len(folder1.contents) == len(folder2.contents)
    
    for entry in folder1.contents:
        f2entry=getEntry(folder2, entry)
        assert f2entry
        if f2entry.oclIsKindOf(L.FileSystem.Folder):
            cmpFolders(f2entry, entry)
        if f2entry.oclIsKindOf(L.FileSystem.File):
            cmpEntry(f2entry, entry)


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

model = prj.contents()[0]

### Delete old test data

import os
os.system("rm -Rf tmp/*")

### Delete end

print "-Test Start- "*3

assert model.oclIsKindOf(L.Package)

for elem in model.ownedElement:
    if elem.oclIsKindOf(L.FileSystem.Folder):
        testFolder(elem)
        elem.commit("tmp/")
    if elem.oclIsKindOf(L.FileSystem.File):
        assert elem.__type__().getOperations()>0
        elem.commit("tmp/")
        

folder=L.FileSystem.Folder()
folder.retrieve("tmp/code")

model2=L.Package()
model2.name="filesystem"
model2.ownedElement.append(folder)
prj=coral.Project()
model2.__setProject__(prj)

prj.setFilename("tmp/CoralExFileSystemRetrieve.xml")
prj.setXMIFormat("2.0")
coral.saveDocument(prj)

## Load two xml files and compare contents

prj3 = coral.loadDocument("tmp/CoralExFileSystemRetrieve.xml")

model3 = prj3.contents()[0]

cmpFolders(model.ownedElement[0], model3.ownedElement[0])

print "-Test End- "*3

