import os


from Ft.Ods.StorageManager.Adapters import Constants
from Ft.Ods import Database
import os,sys
import test_util

odl_string = """
module Test {

class Professor;

class Student (extent students)
{
	attribute string name;
};

class Professor
{
        attribute dictionary <string,Student> students;
};
};

"""
#"


DBNAME=os.environ.get("ODS_TEST_DB","ods:test")

def Test(tester):
    try:
        _Test(tester)
    finally:
        if os.path.exists('Test'):
            from distutils import dir_util
            dir_util.remove_tree('Test')

def _Test(tester):

    tester.startGroup('Basic Dictionary Test %s Driver' % tester.ods_driver_name)

    test_util.DbInit(DBNAME,odl_string)

    tester.startTest('Testing Generated syntax')
    try:
        from Test import Professor
        from Test import Student
    except:
        tester.error('Error in syntax', 1)
    tester.testDone()

    reload(Professor)
    reload(Student)
    
    db = Database.Database()
    db.open(DBNAME)

    tx = db.new()
    tx.begin()

    tester.startTest('Testing Accessing a new dictionary')

    p = Professor.new(db)
    s = Student.new(db)
    s2 = Student.new(db)

    s.name = "Student 1"
    s2.name = "Student 2"

    p.students[s.name] = s
    p.students[s2.name] = s2
    tester.compare(s,p.students["Student 1"])
    tester.compare(s2,p.students["Student 2"])
    tx.commit()
    tester.testDone()


    tester.startTest('Testing Loading and Changing')
    
    pid = p._4ods_getOid()
    sid = s._4ods_getOid()
    s2id = s2._4ods_getOid()

    tx = db.new()
    tx.begin()

    p = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,pid)
    s = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,sid)
    s2 = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,s2id)

    tester.compare(s,p.students["Student 1"])
    tester.compare(s2,p.students["Student 2"])

    tester.compare(2,len(p.students.keys()))
    tester.compare(2,len(p.students.values()))
    del p.students["Student 1"]
    tester.compare(1,len(p.students.keys()))
    tester.compare(1,len(p.students.values()))
    tx.commit()

    tester.testDone()

    tester.startTest('Testing Reload')

    tx = db.new()
    tx.begin()

    p = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,pid)
    s = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,sid)
    s2 = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,s2id)

    tester.compare(1,len(p.students.keys()))
    tester.compare(1,len(p.students.values()))
    tester.compare(0,p.students.has_key('Student 1'))

    tx.abort()
    db.close()
    tester.testDone()
    tester.groupDone()

    return

if __name__ == '__main__':


    from Ft.Lib import TestSuite
    tester = TestSuite.TestSuite(1, 1)
    from Ft.Ods.StorageManager import Adapters
    tester.ods_driver_name = Adapters.g_driverName

    retVal = Test(tester)
    sys.exit(retVal)

