#!/usr/bin/env python3
# SPDX-License-Identifier: MIT

import sys
import json
import csv
import argparse
import matplotlib.pyplot as plt

__version__ = '0.3.1'

def plot_histogram(filename):
    with open(filename) as file:
        rawdata = json.load(file)

    cpu_id = 0
    fig, ax = plt.subplots()
    while True:
        if str(cpu_id) not in rawdata['cpu']:
            break

        cid = str(cpu_id)
        data = rawdata['cpu'][cid]
        d = {int(k): int(v) for k, v in data['histogram'].items()}
        l = 'cpu{} min{:>3} avg{:>7} max{:>3}'.format(
            cid,
            rawdata['cpu'][cid]['min'],
            rawdata['cpu'][cid]['avg'],
            rawdata['cpu'][cid]['max'])
        ax.bar(list(d.keys()), list(d.values()), log=True, alpha=0.5, label=l)

        cpu_id = cpu_id + 1

    L = ax.legend()
    plt.setp(L.texts, family='monospace')
    plt.show()


def plot_samples(filename):
    x = []
    y = []

    with open(filename,'r') as csvfile:
        plots = csv.reader(csvfile, delimiter=';')
        for row in plots:
            x.append(float(row[1]))
            y.append(int(row[2]))

    plt.plot(x,y)
    plt.xlabel('timestamp')
    plt.ylabel('latency (us)')
    plt.legend()
    plt.show()


def main():
    ap = argparse.ArgumentParser(description='Plot statistics collected with jitterdebugger')
    ap.add_argument('--version', action='version',
                    version='%(prog)s ' + __version__)
    sap = ap.add_subparsers(dest='cmd')

    hrs = sap.add_parser('hist', help='Print historgram')
    hrs.add_argument('HIST_FILE')

    srs = sap.add_parser('samples', help='Plot samples graph')
    srs.add_argument('SAMPLE_FILE')

    args = ap.parse_args(sys.argv[1:])
    if args.cmd == 'hist':
        plot_histogram(args.HIST_FILE)
    elif args.cmd == 'samples':
        plot_samples(args.SAMPLE_FILE)

if __name__ == '__main__':
    main()
