#!/usr/bin/python

import serial
import json
from datetime import datetime

JSON_PATH = './Alkator.json'

data_dict = ''

try:
    with open(JSON_PATH, 'r') as file:
        file_content = file.read()
        data_dict = json.loads(file_content)
        print('json_exists')
except:
    data_dict = {}

def get_seconds():
    current_time = datetime.now()
    hours = current_time.hour
    mins = current_time.minute
    secs = current_time.second
    us = current_time.microsecond
    seconds = hours*3600 + mins*60 + secs
    seconds = float(str(seconds) + '.' + str(us))
    return seconds

def read(ser):
    while True:
        mes = ser.read_until(b'\r')
        if b'Reading ntag' in mes:
            print('reading')
        if b'Data' in mes:
            data = mes.decode('utf-8')
            data = data[6:].replace('\x00', '').replace('\r', '').split(' ')
            print('data read done')
            try:
                lap_secs = get_seconds() - data_dict[data[0]]['time']
                print(lap_secs)
                lap = data_dict[data[0]]['laps']
                try:
                    data_dict[data[0]]['lap_time'][lap] = lap_secs
                except:
                    data_dict[data[0]]['lap_time'] = {lap: lap_secs}
                lap += 1
                data_dict[data[0]]['laps'] = lap
                data_dict[data[0]]['time'] = get_seconds()

            except:
                data_dict[data[0]] = {'name': data[1]}
                data_dict[data[0]]['time'] = get_seconds()
                data_dict[data[0]]['laps'] = 0

            data_json = json.dumps(data_dict, indent=4)
            print(data_json)
            with open(JSON_PATH, 'w') as file:
                file.write(data_json)

def write(ser):
    while True:
        data = input('ID:')
        data = data + '\r'
        ser.write(data.encode())
        while True:
            mes = ser.read_until(b'\r')
            if b'Waiting' in mes:
                print('Waiting for card')
            if b'Erasing' in mes:
                print('Erasing card')
            if b'Writing' in mes:
                print('Writing data to card')
            if b'done' in mes:
                print('Write done')
                break

def main():
    s = serial.Serial(port="/dev/ttyACM3", parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=1)
    s.flush()

    rw = input('Read or Write tags? [R/w]')
    rw = rw.lower()

    if rw == 'w':
        s.write('w\r'.encode())
        write(s)
    elif rw == 'r':
        s.write('r\r'.encode())
        read(s)
    elif rw == '':
        s.write('r\r'.encode())
        read(s)
    else:
        print('Invalid option')




if __name__ == "__main__":
        main()
