#!/usr/bin/env python
# Copyright Trimble Inc. 2020
usage="""\
 Plot NTP statistics from several servers to compare them.
 Example usage for comparing lockbox and 10.1.123.456:
   ./ntp_monitor.py stats.txt lockbox 10.1.123.456
   # Ctrl-C after you've logged for a while (1+ hours)
   ./ntp_plot.py stats.txt
"""
from mutils import *
from datetime import datetime, timedelta
from dateutil import tz

def main(filename):
    d=doload(filename)
    fields = []
    receivers = []
    for n,line in enumerate(open(filename,'r')):
        if not line.startswith('%'):
            break
        if line.startswith('% N '):
            fields = line[2:].split()
        elif line.startswith('% N='):
            receivers.append( line.rstrip().split()[-1] )
    k = dict([(a,b) for b,a in enumerate(fields)])
    d = VdCls( d, k, [] )

    utc = tz.tzutc()
    t = []
    for ts in d.recv_time:
        dtime = datetime.fromtimestamp(ts,tz=utc)
        week_start = datetime( dtime.year, dtime.month, dtime.day,tzinfo=utc ) \
                   - timedelta(days=dtime.weekday()+1)
        t.append( (dtime - week_start).total_seconds() )
    t = array(t)

    fig,ax=subplots(3,1,sharex=True)
    for n in unique(d.N):
        i = find(d.N==n)
        d0 = d[i]
        t0 = t[i]
        ax[0].plot( t0, d0.delay )
        ax[1].plot( t0, d0.offset )
        ax[2].plot( t0, d0.root_dispersion )

    ax[0].set_ylabel('delay[s]')
    ax[1].set_ylabel('localhost offset[s]')
    ax[2].set_ylabel('dispersion[s]')
    ax[2].set_xlabel('GPS secs in week')
    figlegend(receivers)

    show()

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=usage,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('filename', help='input filename')
    args = parser.parse_args()
    main( args.filename )
