from Ft.Ods.StorageManager import Adapters
from Ft.Ods.Tools import destroy
from Ft.Ods.Tools import create
from Ft.Ods.Parsers.Odl import Processor
import os,sys, tempfile, profile, pstats

from Ft.Ods import Database


odl_string = """

module Test {

class Person (extent people)
{
	attribute string name;
        attribute string ssn;
        relationship list<Person> influenced_from inverse Person :: influences;
        relationship list<Person> influences inverse Person :: influenced_from;
};

class Professor;

class Student extends Person
{
	relationship Professor learns_from inverse Professor :: teaches;
};

class Professor extends Person
{
	relationship list<Student> teaches inverse Student :: learns_from;
};

};
"""
#"

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

def profile_db_create():

    if Adapters.GetManager().exists(DBNAME):
        destroy.Run({},{'dbName':DBNAME})
    create.Run({},{'dbName':DBNAME})
    processor = Processor.Processor(DBNAME)
    processor.runString(odl_string)
    return

NUM=500

def profile_object_create():
    
    from Test import Professor
    from Test import Student
    db = Database.Database()
    db.open(DBNAME)

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

    for ctr in range(NUM):
        p = Professor.new()
        s = Student.new()

        sInfluenced = Student.new()

        p.name = "Prof"
        s.name = "Stud"
        sInfluenced.name = "Inf"

        s.learns_from = p
        p.add_influences(sInfluenced)

    tx.commit()


tests = [#'profile_db_create',
         'profile_object_create',
         ]

def run_test(outFile,testName):

    tempFileName = tempfile.mktemp()
    prof = profile.Profile()

    prof.runctx("%s()"%testName,globals(),locals())
    prof.dump_stats(tempFileName)

    return tempFileName


def test(fileName):


    #Create the DB
    profile_db_create()
            
    f = open(fileName,'w')
    oldOut = sys.stdout
    sys.stdout = f
    print "Profile Run"

    for t in tests:
        print '*'*20
        print "Running test %s" % t
        print '*'*20
        sf = run_test(fileName,t)
        print "Dump Stats for %s" % t[0]
        pstat = pstats.Stats(sf)
    
        print "Sorted by total cumulative time"
        pstat.strip_dirs().sort_stats('time').print_stats(100)
        print "Sorted by number calls time"
        pstat.strip_dirs().sort_stats('calls').print_stats(100)
        print "A Listing of who called who"
        pstat.print_callers(50)
        print "A Listing of who was called by who"
        pstat.print_callees(50)
        del pstat
        os.unlink(sf)

    sys.stdout = oldOut


if __name__ == '__main__':

    import sys
    outFile = "profile.out"
    if len(sys.argv) > 1:
        outFile = sys.argv[1]
    test(outFile)
