import os


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

odl_string = """
module Test {

  struct Address {
    string street;
    string city;
    string state;
    string zipcode;
  };

  class Person {
    attribute string name;
    attribute Address address;
  };
};

"""
#"


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('Structure Test %s driver' % tester.ods_driver_name)

    test_util.DbInit(DBNAME,odl_string)

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

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

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

    tester.startTest('Testing Structure 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.address,'street'))
    tester.compare(1,hasattr(p.address,'city'))
    tester.compare(1,hasattr(p.address,'state'))
    tester.compare(1,hasattr(p.address,'zipcode'))

    p.address.street = 'A Street'
    p.address.city = 'A City'
    p.address.state = 'A State'
    p.address.zipcode = 'A Zipcode'

    tx.commit()
    tester.testDone()


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

    p = db.lookup('Person')

    tester.compare('A Street',p.address.street)
    tester.compare('A City',p.address.city)
    tester.compare('A State',p.address.state)
    tester.compare('A Zipcode',p.address.zipcode)

    p.address.street = "Another Street"
    p.address.city = 'Another City'
    p.address.state = 'Another State'
    p.address.zipcode = 'Another Zipcode'

    tx.commit()
    tester.testDone()

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

    p = db.lookup('Person')

    tester.compare('Another Street',p.address.street)
    tester.compare('Another City',p.address.city)
    tester.compare('Another State',p.address.state)
    tester.compare('Another Zipcode',p.address.zipcode)


    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)

