#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import argparse
import sys

import matplotlib.pyplot as plt
import yaml

import stressberry


def _main(args):

    data = [yaml.load(f) for f in args.infiles]

    # sort the data such that the data series with the lowest terminal
    # temperature is plotted last (and appears int he legend last)
    terminal_temps = [d['temperature'][-1] for d in data]
    order = [
        i[0] for i in sorted(enumerate(terminal_temps), key=lambda x: x[1])
        ]
    # actually plot it
    for k in order[::-1]:
        plt.plot(
            data[k]['time'], data[k]['temperature'],
            label=data[k]['name']
            )

    plt.grid()
    plt.legend(loc='upper left', bbox_to_anchor=(1.03, 1.0), borderaxespad=0)
    plt.xlabel('time (s)')
    plt.ylabel('temperature (°C)')
    plt.xlim([data[-1]['time'][0], data[-1]['time'][-1]])

    if args.outfile is not None:
        plt.savefig(args.outfile, transparent=True, bbox_inches='tight')
    else:
        plt.show()
    return


def _parse_cmd_arguments():
    parser = argparse.ArgumentParser(
        description='Plot stress test data.'
        )
    parser.add_argument(
        '-v', '--version',
        help='display version information',
        action='version',
        version='stressberry {}, Python {}'.format(
            stressberry.__version__, sys.version
            )
        )
    parser.add_argument(
        'infiles',
        nargs='+',
        type=argparse.FileType('r'),
        help='input YAML file(s) (default: stdin)'
        )
    parser.add_argument(
        '-o', '--outfile',
        help=(
            'if specified, the plot is written to this file '
            '(default: show on screen)'
            )
        )
    return parser.parse_args()


if __name__ == '__main__':
    _main(_parse_cmd_arguments())
