from net.grinder.script.Grinder import grinder
import os
import sys
import cPickle

OUT_DIR = 'data'

def import_data(module):
    try:
        x = __import__(module)
        # reload the module in case the data has changed on the disk
        reload(x)
        try:
            return x.data
        except AttributeError:
            return {}
    except ImportError:
        return {}

def export_data(module, dic, outdir = '.'):
    f = open(outdir + '/' + module + '.py', 'w')
    f.write('# ' + module + '\ndata = ')
    f.write(repr(dic))
    f.write('\n')
    f.close()

def read_data(module, outdir = '.'):
    if os.path.exists(outdir + '/' + module + '.dat'):
        f = open(outdir + '/' + module + '.dat', 'r')
        data = cPickle.load(f)
        f.close()
        return data
    return {}

def write_data(module, dic, outdir = '.'):
    f = open(outdir + '/' + module + '.dat', 'w')
    cPickle.dump(dic, f)
    f.close()

def setup_thread():
    sys.path.append(os.environ['GRINDERPATH'] + '/' + OUT_DIR)


def thread_user_data():
#    user_data = { 'username': 'user' + str(1 + grinder.threadNumber), 'password' : 'pass'}
    user_data = { 'username': 'admin', 'password' : 'pass'}
    grinder.getLogger().output('user_data = ' + str(user_data))
    return user_data

def make_thread_filename(module):
    '''Create a thread specific file name, that is also appropriate as a Java class name'''
    name = os.path.basename(grinder.getFilenameFactory().createFilename(module, ''))
    name = name.replace('-', '_') # can't have - in a java class name
    return name

def read_thread_data(module, mergeWithNonThreadData=True):
    '''Read data specific for this thread'''
    #import sys
    #grinder.logger.output('sys.path=' + str(sys.path))
    dic = {}
    if mergeWithNonThreadData:
        dic = import_data(module)
        grinder.getLogger().output('read (for merging) ' + str(dic) + ' from ' + module)
    threadModule = make_thread_filename(module)
    grinder.getLogger().output('reading from ' + threadModule)
    dic.update(read_data(threadModule, OUT_DIR))
    grinder.getLogger().output('merged input is ' + str(dic))
    return dic

def write_thread_data(module, dic, mergeWithNonThreadData=True):
    '''Write data specific for this thread'''
    # merge
    if mergeWithNonThreadData:
        x = import_data(module)
        x.update(dic)
        dic = x

    threadModule = make_thread_filename(module)
    grinder.getLogger().output('writing' + str(dic) + ' into ' + threadModule)
    write_data(threadModule, dic, OUT_DIR)
