import os

odl_string = '''

typedef long myLong;
typedef short myShort;
typedef string myString;

module Test {
  const myShort myConst = 15;

  class Foo;

  enum TestEnum {e1};
  typedef TestEnum myEnum;

  struct TestStruct {
    myString st;
  };

  typedef TestStruct myStruct;
  

  class Bar {
    attribute myLong l;
    attribute myEnum e;
    attribute myStruct s;
    relationship Foo f inverse Foo::mb;
    };

  typedef Bar myBar;


class Foo {

  attribute myShort s;
  attribute myBar b;
  relationship myBar mb inverse myBar::f;
  attribute list<myLong> ll;
};
};
'''

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

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

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("TypeDefs %s Driver" % tester.test_data['driver'])

    test_util.DbInit(DBNAME,odl_string)

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


    tester.testDone()

    db = Database.Database()
    db.open(DBNAME)
    try:
        tx = db.new()
        tx.begin()

        #Create an instance of Foo and some bars to play with
        tester.startTest("Create Instances")
        f = Foo.new(db)
        f.s = 1
        b1 = Bar.new(db)
        b1.l = 2
        b1.e = Test.TestEnum.e1
        b1.s.st = 'String'
        b2 = Bar.new(db)
        f.form_mb(b1)
        f.b = b2
        db.bind(f,"Foo")
        tx.commit()
        tester.testDone()

        tester.startTest("Reload and test Types")

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

        foo = db.lookup("Foo")
        tester.compare(1,type(Test.myConst) == type(1))
        tester.compare(1,isinstance(f.b,Bar.Bar_stub))
        tester.compare(1,isinstance(f.mb,Bar.Bar_stub))
        tester.compare(1,type(f.s) == type(1))
        tester.compare(1,type(f.mb.l) == type(1))
        tester.compare(Test.TestEnum.e1,foo.mb.e)
        tester.compare('String',foo.mb.s.st)

        tx.commit()
        tester.testDone()

        tester.testDone()

    finally:
        db.close()
    tester.groupDone()



