#!/usr/bin/env python3
"""
Create peakworks-compatible measurement (for easy comparison):

    while true ; do
        echo \
             $(date +%D-%R:%S) \
             $(echo -n 'IPW        T1600000999650T1  1  1     DEUDEUI5006LMX59995999587 7' \
                 | nc -v -w 5 10.22.4.10 9726 2>&1 \
                 | egrep "(second|timed out|fatal)" \
                 | awk 'END {print $(NF-1),$NF}'\
             ) \
             >> /opt/stadis_log_$(date --iso-8601).txt;
         sleep 10
     done


pip3 install numpy plotxt
"""

import time
import plotext as plt
import sys
import os
import datetime
import numpy as np

try:
	LOG_FILE = sys.argv[1]
except IndexError:
    LOG_FILE  = 'lmx_2022-01-06.log'
    #sys.stderr.write(f'Usage: {sys.argv[0]} LOG_FILE' + os.linesep)
    #sys.exit(1)

## major tick on datime scale, calculation base
RT_BINS= [ -2,0,2,4,6,8,10,15,20,30 ]

# filter data
def read_timeseries():
    """retreive datime and float values from text file"""

    # format input data
    plt.datetime.set_datetime_form('%m/%d/%y-%H:%M:%S')
    with open(LOG_FILE, 'r') as infile:
        for line in infile.readlines():
            datetime_str = line.split()[0]
            date_str, time_str = datetime_str.split('-')
            current_dt = plt.datetime.string_to_datetime(datetime_str)
            try:
                rt = int(float(line.split()[1]) + 0.5) # response time
            # timeout, no response
            except ValueError:
                rt = -1
            # no value, last measurement too long
            except IndexError:
                rt = -2

            finally:
                yield(current_dt, rt)

hour_series = []
last_hour = 0
all_rts = []
for dt, rt in read_timeseries():

    all_rts.append(rt)

    # detect going to next hour
    if (dt.hour > last_hour) or (dt.hour == 0 and dt.hour < last_hour):

        # analyse data of this hour - calc max of values
        try:
            max_3s = int(np.mean(this_hour_rts) + np.std(this_hour_rts) * 3 + 0.5)
            hour_series.append([dt, max_3s])
        except NameError:
            pass

        # prepare next hour
        this_hour_rts = [rt]
        last_hour = dt.hour


    # or store current_hour_data
    else:
        try:
            this_hour_rts.append(rt)
        except NameError:
            this_hour_rts = [rt]
    
dates = [str(hs[0]) for hs in hour_series]
rts   = [hs[1] for hs in hour_series]

plt.datetime.set_datetime_form('%Y-%m-%d %H:%M:%S')
"""
plt.bar(dates, rts)
plt.title('LMX response times')
plt.xlabel('Date')
plt.ylabel('Tobri response time [s]')
plt.ylim(-2, 30)
plt.yticks(RT_BINS)
"""
print(RT_BINS)
plt.hist(all_rts, 20, label='Freqency response times')
plt.xlim(-2, 30)
#plt.xfrequency(10)
plt.show()


data = []



