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

from Query import Query
from Node import Node
import sys

fIn = 'dumpQuery_' + sys.argv[1] + '.txt'
fOut1 = 'QueryTrace_' + sys.argv[1] + '.txt'
fOut2 = 'NodeTrac_' + sys.argv[1] + '.txt'

path = []
nodes = {}

fdIn = open(fIn, 'r')
fdOut1 = open(fOut1, 'w')
for line in fdIn: #Extract path information
    tmp = line.split()
    if len(tmp) == 0: continue #Skip blank lines
    if tmp[0] == 'PATH':
        if ((len(tmp) - 4) != (int(tmp[-1]) + 1)) and (tmp[3] != tmp[4]):
            print 'Path length & no of intermediate nodes don\'t match'
            print tmp
            sys.exit(0)
        elif len(tmp) == 5: #Query resolved at same node
            print tmp
            tmp.insert(4, tmp[3])
            sys.exit(0)
        path.append(Query(tmp[2], tmp[3:-1]))
        for i in range(len(tmp) - 2):
            fdOut1.write(tmp[i + 2] + '\t')
        fdOut1.write('\n')
fdIn.close()
fdOut1.close()

#Extract node information
for i in path:
    for j in range(len(i.path)):
        if i.path[j] not in nodes: #Check whether node is already in list
            nodes[i.path[j]] = Node(i.path[j]) #Add new node
        if j > 0  and (i.path[j] != i.path[j - 1]): #Not the source node & src & dst not same
            if i.key not in nodes[i.path[j]].traffic: #New key
                nodes[i.path[j]].traffic[i.key] = {i.path[j - 1]: 1}
            else: #Update info for old key
                if i.path[j - 1] not in nodes[i.path[j]].traffic[i.key]:
                    if len(nodes[i.path[j]].traffic[i.key]) > 0:
                        nodes[i.path[j]].traffic[i.key][i.path[j - 1]] = 1
                    else:
                        nodes[i.path[j]].traffic[i.key] = {i.path[j - 1]: 1}
                else: #Already there
                    nodes[i.path[j]].traffic[i.key][i.path[j - 1]] += 1
        if j == len(i.path) - 1: #Add key indexed as successor
            if i.key not in nodes[i.path[j]].idx: #If not already in index
                nodes[i.path[j]].idx.append(i.key)

#Dump node information
fdOut2 = open(fOut2, 'w')
for i in nodes:
    #Get node ID + no of keys in index
    tmpStr = i + '\t' + str(len(nodes[i].idx))
    for j in nodes[i].idx: tmpStr += '\t' + j 
    for j in nodes[i].traffic:
        tmpStr += '\t' + j + '\t' + str(len(nodes[i].traffic[j]))
        for k in nodes[i].traffic[j]:
            tmpStr += '\t' + k + '\t' + str(nodes[i].traffic[j][k])
    fdOut2.write(tmpStr + '\n')
fdOut2.close()
    
    
