#!/usr/bin/python3

import os
import sys
import statistics
import matplotlib.pyplot as plt

def parse_capture(filename):
    f = open('measurements/' + filename)
    # Skip the first two false positves (risky)
    counter = -1
    lets_use_a_flag = False
    six_ts = ''
    two_ts = ''
    enc_deltas = {}
    dec_deltas = {}
    for l in f.readlines():
        l_array = l.split(" ")
        bit_field = l_array[-1][:-1]
        # l_array? That's the best you came up with?
        if bit_field == '2':
            two_ts = l_array[0][:-1]
            lets_use_a_flag = True
            continue
        if lets_use_a_flag:
            if bit_field == '6':
                if counter <= 0:
                    counter = counter + 1
                    lets_use_a_flag = False
                    continue
                six_ts = l_array[0][:-1]
                delta = float(six_ts) - float(two_ts)
                if counter % 2 == 1:
                    enc_deltas[(counter+1)/2] = delta
                else:
                    dec_deltas[counter/2] = delta
                counter = counter + 1
            else:
                lets_use_a_flag = False
    f.close()
    return (enc_deltas, dec_deltas)

def read_log(d):
    # Soo readlines, much efficient
    f = open(d + '/test_stdout.log', 'r')
    content = f.readlines()

    are_we_happy = content[-1].split(' ')[-1]
    if are_we_happy != 'SUCCESSFUL\n':
        print ("Test unsuccesful or log file structure corrupted")
        return

    # I like to split it, split it 
    path = content[0].split(' ')[-1].split('/') 
    if path[-2] == 'ref':
        algorithm = path[-3]
    else:
        algorithm = path[-2]

    # Path to logic data is in the second to last line
    logic_file = content[-2].split('/')[-1][:-2]

    f. close()

    print("Evaluating results for %s" % (algorithm))

    dicts = parse_capture(logic_file)

    return (algorithm, dicts)

def gen_graph_chunks(bp_data, bp_labels, size):
    l = len(bp_data)
    for i in range(0, (l//size) * size, size):
        chunk = bp_data[i:i+size]
        labels = bp_labels[i:i+size]
        plt.boxplot(chunk, labels=labels)
        plt.xticks(rotation=90)
        plt.show()
    # Let's also plot the leftover
    rest = l % size
    if rest != 0:
        plt.boxplot(bp_data[(rest-2*rest):])
        plt.show()

def main():
    print('THE LWC BENCHMARK SPLITTER')
    print('powered by Deutsche Bahn')
    build_dir = 'build/new/'
    bp_data = []
    bp_labels = []
    for d in os.listdir(build_dir):
        #dicts[0] --> algo
        #dicts[1][0] --> enc
        #dicts[1][1] --> dec
        dicts = read_log(os.path.join(build_dir + d))
        enc_values = dicts[1][0].values()
        dec_values = dicts[1][1].values()
     
        bp_data.append(list(enc_values))
        bp_labels.append(dicts[0])

        print("Average enc time[s] = %f" % (statistics.mean(enc_values)))
        print("Median enc time[s] = %f" % (statistics.median(enc_values)))
        print("Average dec time[s] = %f"  % (statistics.mean(dec_values)))
        print("Median dec time[s] = %f"  % (statistics.median(dec_values)))
        print()
        
        enc_len = len(dicts[1][0])
        dec_len = len(dicts[1][1])

        if dec_len != enc_len:
            raise Exception("#Encryptions (%d) does not match #decryptions (%d)" % (enc_len, dec_len))

        if dec_len != 1089 or enc_len != 1089:
            raise Exception("#Number of encrypted test vectors (%d)/ decrypted test vectors (%d) does not match guidelines (1089)" % (enc_len, dec_len))

    gen_graph_chunks(bp_data, bp_labels, 5) 
    #plt.boxplot(bp_data, labels=bp_labels)
    #plt.xticks(rotation=90)
    #plt.show()
if __name__ == "__main__":
    main()

