import sys, getopt, os, subprocess
import settings
import networkx as nx

inputSubDir = ''
delimiter = ' '
directed = False
networkConstructionType = ''
minT0 = 0

opts, args = getopt.getopt(sys.argv[1:], "s:d:i:m:th", ["subdir,help,directed,minT"])
for o, a in opts:

    if o in ('-s', '--subdir'):
        inputSubDir = a  + '/'
    elif o == '-d':
        delimiter = a.strip()
        if delimiter == 'tab':
            delimiter = '\t'
    elif o =='--directed':
        directed = True
    elif o in ('-m','--minT'):
        minT0 = int(a)
    elif o == '-i':
        networkConstructionType = a.strip()
    if o in ('-h','--help'):
        print """Usage:
%s network_name threshold
-s,--subdir      Input/output subdirectory
-i               Input location within network input directory (e.g., type of threshold or deltaT used for snapshot construction or simply location of temporal network file) - default "snapshots"
-d               Delimiter (use 'tab' for '\\t')
--minT0          When aggregating form a temporal network, minimum time of records to consider (e.g., ignore all "t u v"  such that t < minT0)
-h,--help        Print this""" % sys.argv[0]
        sys.exit(0)

networkName = args[0]
threshold = int(args[1])


outputDir = settings.BASE_INPUT_DIR+ inputSubDir + networkName + '/' + 'aggregated/'

print 'Aggregating snapshots for %s network...' % networkName

if (not '.txt' in networkConstructionType and networkConstructionType != '') or not os.path.exists(settings.BASE_INPUT_DIR + inputSubDir + networkName + '/' + networkName + '.txt'):
    inputDir = settings.BASE_INPUT_DIR + inputSubDir + networkName + '/' + 'snapshots/' + networkConstructionType
    inputFileList = sorted([os.path.join(inputDir, f) for f in os.listdir(inputDir)])
    inputFiles = ','.join(inputFileList)

    print 'List of snapshots (%s files): %s' % (len(inputFileList),inputFiles)
else:
    if networkConstructionType == '':
        networkConstructionType = networkName + '.txt'

    inputDir = settings.BASE_INPUT_DIR + inputSubDir + networkName + '/'
    inputFileList = [os.path.join(inputDir,networkConstructionType)]
    print 'Aggregating temporal network %s...' % inputFileList[0]

if not os.path.exists(outputDir):
    os.makedirs(outputDir)

nodes = set()
edges = dict()


for f in inputFileList:
    for line in file(f).readlines():
        values = line.strip().split(delimiter)

        if not '.txt' in networkConstructionType:
            if len(values) != 2:
                print 'Error: %s' % values

            node1 = values[0]
            node2 = values[1]
        else:
            if len(values) != 3:
                print 'Error: %s' % values
            if int(values[0]) < minT0:
                continue
            node1 = values[1]
            node2 = values[2]

        nodes.add(node1)
        nodes.add(node2)

        #remove self-loops
        if node1 == node2:
            continue

        if not directed:
            node_pair = (min(node1,node2),max(node1,node2))
        else:
            node_pair = (node1,node2)

        if edges.has_key((node1,node2)):
            edges[(node1,node2)] += 1
        else:
            edges[(node1,node2)] = 1


inputTypeSubDirTrimmed = networkConstructionType.replace(networkName,'').replace('.txt','').replace('\\','')
outputFileName = outputDir + networkName + ('' if (inputTypeSubDirTrimmed == '' or inputTypeSubDirTrimmed[0]=='_') else '_') + inputTypeSubDirTrimmed + '_aggregated_%s.txt' % threshold

G = nx.Graph() if not directed else nx.DiGraph()
with open(outputFileName, mode='wb') as outputFile:
    for nodePair in sorted(edges.keys()):
        if edges[nodePair] >= threshold:
            G.add_edge(nodePair[0],nodePair[1])

nx.write_edgelist(nx.Graph(G), outputFileName, delimiter=delimiter, data=False)

print 'Saved aggregated network (%s nodes and %s edges) to %s' % (G.order(),G.size(), outputFileName)
