#!/usr/bin/env python3

import os
import sys
import subprocess

from bwparser import BandwidthParser

# Plot the bandwidth files using gnuplot

if __name__ == '__main__':
    if len(sys.argv) != 2:
        sys.stderr.write("Usage: outputdir\n")
        sys.exit(1)

    # set some defaults
    bandwidth_file = os.getenv('BW_FILE')
    output_dir = sys.argv[1]
    output_file = output_dir + "/bw_file.pdf"

    # calculate invariants
    bw_parser = BandwidthParser(bw_file=bandwidth_file)
    network_size = bw_parser.get_relay_num()

    # Create dat files and gpcode
    gpcode = """set terminal pdf font "DejaVuSans,14" size 5,2.25
        set output '%s'
        set title 'Bandwidth distribution'
        set key out
        set xlabel "Bandwidth (kB/s)"
        set ylabel "Number of relays"
        set xtics 100000
        plot """ % (output_file)


    for bw_file in bw_parser.get_files():
        local_bw_parser = BandwidthParser(bw_file=bw_file)
        bandwidths = local_bw_parser.get_distribution()

        with open("%s.dat" % bw_file, "w") as datout:
            for i in range(len(bandwidths)):
                datout.write("%s %s\n" % \
                        (i, bandwidths[i]))
            datout.close()

        date_string = bw_file.split("-")[0] + "-" + bw_file.split("-")[1] + "-" + bw_file.split("-")[2]

        gpcode += "'%s.dat' using 2:1 with lines title '%s'," % (bw_file, date_string)

    gp = subprocess.Popen(['gnuplot', '-'], stdin=subprocess.PIPE)
    gp.communicate(gpcode.encode('ascii'))
