import csv
import os
from pdb import set_trace as debugger

MAIN_CODE_DIR = os.environ.get('MAIN_CODE_DIR', '')

def read_centrality_score(filepath):
    scores = dict()
    with open(filepath) as f:
        csv_reader = csv.reader(f)
        try:
            for row in csv_reader:
                if len(row) != 2:
                    print row
                scores[row[0]] = row[1]
        except Exception as e:
            print e
            return 0

    return scores

def sort_value_of_dictionary(dictionary):
    l = list()
    for k, v in dictionary.iteritems():
        l.append((k, v))

    l.sort(key=lambda tup: tup[1])
    return l


if __name__ == '__main__':
    filepath_prefixes = ['/output/networkx_', '/output/weight_basic_', '/output/heuristic_']
    types = ['edge_list']
    extension = '.csv'

    for t in types:
        # TODO: any other way to handle the relative path???
        filepaths = [MAIN_CODE_DIR + p + t + extension for p in filepath_prefixes]

        nx_scores = read_centrality_score(filepaths[0])
        weight_basic_scores = read_centrality_score(filepaths[1])
        heuristic_scores = read_centrality_score(filepaths[2])

        sorted_nx_scores = sort_value_of_dictionary(nx_scores)

        # write to file
        # FORMAT: ip_address    networkx_centrality     boost_centrality
        print "Compare"
        with open(MAIN_CODE_DIR + '/output/score_summary_%s.txt' % t, 'w') as output:
            for key, nx in sorted_nx_scores:
                weight_basic = weight_basic_scores[key]
                heuristic = heuristic_scores[key]
                output.write('%s\t%s\t%s\t%s\n' % (key, nx, weight_basic, heuristic))


