'''
Created on Sep 1, 2011
@author: Dilum Bandara
@contact: dilumb@engr.colostate.edu
@version: 0.1
@copyright: Copyright(c) 2011, Dilum Bandara
@license: GPL
'''

'''
Generate queries using probabilistic FSM
'''
import random;
import sys;

numQueries = int(sys.argv[1]) #Number of queries to generate
random.seed(1234) #TODO set seed
fIn = 'States.txt'
fOut = 'Queries.txt'

fdIn = open(fIn, 'r')
states = {} #{start state: {next state: num of queries}}
statesTotalQue = {} #Number of total queries outgoing from a state
attbs = []
for line in fdIn:
    tmpLine = line.split()
    if tmpLine[0] in states: #Already added
        states[tmpLine[0]][tmpLine[1]] = [statesTotalQue[tmpLine[0]], statesTotalQue[tmpLine[0]] + int(tmpLine[2])]
        statesTotalQue[tmpLine[0]] += int(tmpLine[2])
    else: #first time
        statesTotalQue[tmpLine[0]] = int(tmpLine[2])
        states[tmpLine[0]] = {tmpLine[1]: [0, int(tmpLine[2])]}
fdIn.close()

fdOut = open(fOut, 'w')
for i in range(numQueries): #Generate queries
    query = ''
    curState = 'START' #Current state. Start from START state
    addAttbs = True
    while addAttbs:
        idx = random.randint(1, statesTotalQue[curState])
        for j in states[curState]:
            if idx > states[curState][j][0] and idx <= states[curState][j][1]:
                if j == 'FINISH':
                    addAttbs = False #Query complete
                else:
                    tmp = j.split('_') 
                    if 'Loc' in j or 'FCNamex' in j:
                        query += tmp[0] + '\t' + tmp[1] + '\t' + tmp[1] + '\t'
                    elif 'NumRes' in j:
                        query += tmp[0] + '\t' + tmp[1] + '\t'
                    elif 'NoAtt' not in j:
                        query += tmp[0] + '\t' + tmp[1] + '\t' + tmp[2] + '\t'
                    curState = j
                break
    fdOut.write(query + '\n')
fdOut.close()
