#!/usr/bin/env python3

import os
import math
import subprocess
import analytical

from bwparser import JansenBandwidthParser

# Plot the dat files generated by parselogs.py using gnuplot

if __name__ == '__main__':

    # sensible defaults
    bandwidth_file = os.getenv('BW_FILE')

    bw_parser = None
    network_size = 0

    if os.getenv('BW_ALGO') != "komlo":
        bw_parser = JansenBandwidthParser(bw_file=bandwidth_file)
        network_size = bw_parser.get_relay_num()
    else:
        # keep the original assumption
        network_size = 6500

    # The analytical functions come from analytical.py
    # Replace 'R' in the output of that program by 'x' and replace
    # 'logR' by 'ceil(log(x)/log(2))'.

    relay_perclient_analyticals = analytical.calculate_relay_analyticals()

    relay_analyticals = {
        k: '(2500000/%s)*(%s)' % (network_size, v) for k, v in relay_perclient_analyticals.items()
    }

    client_analyticals = analytical.calculate_client_analyticals()

    plots = [
        ('dirauth', 'Directory authorities total bytes each', 2, False, None),
        ('relay', 'Relay total bytes each', 4, False, None),
        ('relay_bf', 'Bootstrapping fallback relays bytes per bw', 6, True, None),
        ('relay_f', 'Non-bootstrapping fallback relays bytes per bw', 8, True, None),
        ('relay_b', 'Bootstrapping normal relays bytes per bw', 10, True, None),
        ('relay_n', 'Non-bootstrapping normal relays bytes per bw', 12, True, None),
        ('client', 'Client total bytes each', 14, False, None),
        ('client_c', 'Client circuit building times', 16, True, None),
        ('client_b', 'Bootstrapping client total bytes', 18, True, None),
        ('client_n', 'Non-bootstrapping client total bytes', 20, True, None),
        ('dirauth_ss', 'Directory authority total bytes each', 22, True, None),
        ('relay_ss', 'Relay total bytes each', 24, True, relay_analyticals),
        ('client_ss', 'Client total bytes each', 26, True, client_analyticals),
        ('relay_perclient_ss', 'Relay total bytes per client', 28, True, relay_perclient_analyticals),
        ('relay_ss_wide', 'Relay total bytes each', 24, True, relay_analyticals),
        ('client_ss_wide', 'Client total bytes each', 26, True, client_analyticals),
        ('relay_perclient_ss_wide', 'Relay total bytes per client', 28, True, relay_perclient_analyticals),
    ]

    dats = [
        ('vanilla_none', 'Vanilla', 1),
        ('singlepass_merkle', 'Sing(M)', 2),
        ('telescoping_merkle', 'Tele(M)', 3),
        ('singlepass_threshsig', 'Sing(T)', 4),
        ('telescoping_threshsig', 'Tele(T)', 5),
    ]

    for filename, title, col, errbars, analyticals in plots:
        if analyticals is None:
            analyticals = dict()
        if filename == 'relay_ss_wide':
            ranges = 'set xrange [300:%s]\nset logscale xy\nset yrange [10000000:]' % (network_size*100)
        elif filename[-5:] == '_wide':
            ranges = "set xrange [300:%s]\nset logscale xy\nset yrange [10000:]" % (network_size*100)
        else:
            ranges = "set xrange [0:2200]\nset yrange [0:]"
        gpcode = """set terminal pdf font "DejaVuSans,14" size 5,2.25
set output '%s.pdf'
set title '%s'
%s
set key out
set rmargin 17
set arrow from %s, graph 0 to %s, graph 1 nohead lc 0 lw 2
set xlabel "Number of relays"
set style line 1 lw 2 lc 1 pt 1
set style line 2 lw 2 lc 2 pt 1
set style line 3 lw 2 lc 3 pt 1
set style line 4 lw 2 lc 4 pt 1
set style line 5 lw 2 lc 5 pt 1
set style line 10 lw 2 lc 0 dt 2
set style line 11 lw 2 lc 1 dt 2
set style line 12 lw 2 lc 2 dt 2
set style line 13 lw 2 lc 3 dt 2
set style line 14 lw 2 lc 4 dt 2
set style line 15 lw 2 lc 5 dt 2
plot """ % (filename, title, ranges, network_size, network_size)
        firstplot = True
        for datname, title, style in dats:
            if not firstplot:
                gpcode += ", "
            else:
                firstplot = False

            gpcode += "'%s.dat' using 1:%d with lines ls %d title '%s'" % \
                (datname, col, style, title)
            if errbars:
                gpcode += ", '%s.dat' using 1:%d:%d with errorbars ls %d notitle" % \
                    (datname, col, col+1, style)
            if datname in analyticals:
                gpcode += ", %s ls %d notitle" % \
                    (analyticals[datname], style+10)
        if analyticals:
            gpcode += ", -100 ls 10 title 'Analytical'"

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

