import os

#Test a few threads against both the same and other databases



from Ft.Ods.StorageManager.Adapters import Constants

SLEEP_MAX = .5

odl_string = '''
class Foo
{
	attribute string data;
};

'''
#'

NUM_THREADS = 10

from Ft.Ods import Database
import threading
import time

g_gate = 1

g_dbName = ''

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

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

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

    
def _Test(tester):

    tester.startGroup("mthread test %s Driver" % tester.ods_driver_name)

    test_util.DbInit(DBNAME,odl_string)

    global g_dbName
    g_dbName = DBNAME

    db = Database.Database()
    db.open(g_dbName)

    tester.startTest("Create Threads")

    threads = []
    for ctr in range(NUM_THREADS):
        t = threading.Thread(None,test_thread,"Thread-%i"%ctr,(db,ctr,))
        t.start()
        threads.append(t)

    tester.testDone()
    global g_gate
    g_gate = 0

    tester.startTest("Run Threads")
    left = filter(lambda x:x.isAlive(),threads)
    while len(left):
        time.sleep(1)
        left = filter(lambda x:x.isAlive(),left)
    tester.testDone()
    tester.groupDone()
    db.close()



def test_thread(db,threadNum):
    
    sleepTime = 0
    sTime = time.time()

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

    import Foo
    reload(Foo)

    for ctr in range(10):
        f = Foo.new(db)
        sleepTime = sleepTime + rSleep()
        db.bind(f,"Foo %i %i" % (threadNum,ctr))

    tx.commit()

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

    for ctr in range(10):
        f = db.lookup("Foo %i %i" % (threadNum,ctr))
        f.data = "1"
        sleepTime = sleepTime + rSleep()
    tx.commit()

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

    for ctr in range(10):
        f = db.lookup("Foo %i %i" % (threadNum,ctr))
        f.delete()
        sleepTime = sleepTime + rSleep()
    tx.commit()

    
    eTime = time.time()

import whrandom
generator = whrandom.whrandom()

def rSleep():
    global generator
    sTime = generator.random() * SLEEP_MAX
    time.sleep(sTime)
    return sTime


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)
