#!/usr/bin/env python3

import array, datetime, math, random, statistics, sys
from struct import *

def print_hex(self):
    for byte in self.cmd_bin:
        print("{:x}".format(byte))

def parse_time(time):
    #return datetime.datetime(time[0:4], time[5:
    return datetime.datetime(int(time[0:4]), int(time[5:7]), int(time[8:10]), 
        int(time[11:13]), int(time[14:16]), int(time[17:19]), int(time[20:26]))

def gps_fix(gpstime):
    usec = int((int(gpstime[20:26]) / 666) * (1/1.5e-3))
    if(usec >= 1e6):
        print('error')
    return str(usec).rjust(6, '0')

def time_diff(gpstime, usbtime):
    #diff = usbtime - gpstime
    if usbtime > gpstime:
        if (usbtime - gpstime) > datetime.timedelta(microseconds=127000) or \
		(usbtime - gpstime) < datetime.timedelta(microseconds=114000):
            #print('+', (usbtime - gpstime), gpstime, usbtime)
            gpstime = usbtime - datetime.timedelta(microseconds=115500)
            #print('n', (usbtime - gpstime), gpstime, usbtime)
        return gpstime, usbtime - gpstime 
    elif usbtime < gpstime:
        #print(gpstime, usbtime)
        gpstime = gpstime - datetime.timedelta(seconds=1)
        if (usbtime - gpstime) > datetime.timedelta(microseconds=125000):
            #print('-', (usbtime - gpstime), gpstime, usbtime)
            gpstime = usbtime - datetime.timedelta(microseconds=115500)
        return gpstime, usbtime - gpstime
    else:
        #print('=', usbtime - gpstime, gpstime, usbtime)
        gpstime = usbtime - datetime.timedelta(microseconds=115500)
        return gpstime, usbtime - gpstime

def usb_fix(usbtime):
    rerr = random.randrange(115400,115850)
    usbtime = usbtime - datetime.timedelta(microseconds=rerr)
    return usbtime

def main():
    if len(sys.argv) > 1:
        txt_name = sys.argv[1]
    else:
        print('Not enough cmdline params!')
        return

    diffs = []
    with open(txt_name, 'r') as logf:
        for line in logf:
            syst, gpst = line.split()
            gpstm = gpst[0:20] + gps_fix(gpst)
            gpstm = parse_time(gpstm)
            systm = parse_time(syst[0:23] + syst[24:])
            diff = gpstm - systm
            if diff > datetime.timedelta(seconds=1):
                diff -= datetime.timedelta(seconds=1)
            #print(syst, gpst)
            #print(systm, gpstm, diff) 
            #print()
            print(diff.microseconds)
            diffs.append(diff.microseconds)
            #print(systm, gpstm)

    #print('mean', statistics.mean(diffs))
    #print('median', statistics.median(diffs))
    #print('stdev', statistics.stdev(diffs))
    #print('variance', statistics.variance(diffs))
    #print('max:', max(diffs))
    #print('min:', min(diffs))

    return

    if txt_type == '7z':
        diffs = []
        with open(txt_name, 'r') as logf:
            for line in logf:
                fname, gpst, usbt = line.split()	 
                #print(fname, gpst, usbt)
                gpstm = gpst[0:20] + gps_fix(gpst)
                gpstm = parse_time(gpstm)
                usbt = parse_time(usbt)
                #print(gpst, gpstm)
                gpstm, diff = time_diff(gpstm, usbt)
                if diff < datetime.timedelta(microseconds=10000):
                    print(gpstm, usbt)
                diffs.append(diff.microseconds)
                print(gpstm.isoformat(), diff, fname)
    elif txt_type == 'tar':
        with open(txt_name, 'r') as logf:
            for line in logf:
                fname, usbt = line.split()
                usbt = parse_time(usbt)
                cusbt = usb_fix(usbt)
                print(cusbt.isoformat(), fname)		
    #for diff in diffs:
    #    if 110e3 <= diff <= 130e3 :
    #        print(diff)

if __name__ == '__main__':
    main()

