import os


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

odl_string = """
module Test {

  union MyUnion switch (short) {
    case 1:
    case 2:
      string st;
    case 3:
    case 4:
      long l;
    default:
      boolean b;
  };

  class Person {
    attribute MyUnion u;
  };
};

"""
#"


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')
        pass
    

def _Test(tester):

    tester.startGroup('Union Test %s driver' % tester.ods_driver_name)

    test_util.DbInit(DBNAME,odl_string)

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

    reload(Person)
    reload(Test)
    
    db = Database.Database()
    db.open(DBNAME)

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

    tester.startTest('Testing Union Creation')

    p = Person.new(db)

    p.name = 'Mike Olson'

    if db.lookup('Person'):
        db.unbind('Person')
    db.bind(p,'Person')

    #tester.compare(1,hasattr(p,'u'))
    tester.compare(1,isinstance(p.u,Union.Union))

    tester.compare(None,p.u._d)
    tester.compare(0,p.u._v)

    p.u = Test.MyUnion(1,'A String')

    tx.commit()
    tester.testDone()


    tester.startTest('Testing access and modify Union')
    tx = db.new()
    tx.begin()

    p = db.lookup('Person')

    tester.compare(1,p.u._d)
    tester.compare("A String",p.u._v)
    tester.compare("A String",p.u.st)

    p.u = Test.MyUnion(3,5)

    tx.commit()
    tester.testDone()

    tester.startTest('Testing modified Structure')
    tx = db.new()
    tx.begin()

    p = db.lookup('Person')

    tester.compare(3,p.u._d)
    tester.compare(5,p.u._v)
    tester.compare(5,p.u.l)


    tx.commit()
    tester.testDone()

    db.close()
    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)

