##
# @file    co-ord_capture.py
# @brief   Capture GNSS coordinates at the press of a button
# @author  Jamie Bird (copied and modified from 'simulator_capture.py' by Henry Daitx)
# @date    Sept 2020
# @copyright Racelogic Ltd., 2020
#

import gui
import vbox
import vts
import gnss
from terminal import Terminal

point_no = 1

def capture_cb(b):
    global point_no
    term.set_attr(0x03)
    term.write('Point: {}\n'.format(point_no))
    point_no +=1
    term.set_attr()
    spl = vbox.get_sample()
    term.write('{}, {}\n'.format(spl.lat_minE5, spl.lng_minE5))
    term.write('\n')

def avg_capture_cb(b):
    from math import ceil
    global point_no
    lng_buf = []
    lat_buf = []
    led_prog = [0]*12
    gui_l[2][6] = 'Averaging...'
    while len(lng_buf) < 50:
        spl = vbox.get_sample()
        lng_buf.append(spl.lng_minE5)
        lat_buf.append(spl.lat_minE5)
        prog = ceil(len(lng_buf)/12.5)
        if prog:
            led_prog[0:prog*3] = [0,255,0]*prog
            vts.leds(*led_prog)
        vts.delay_ms(100)
    lng_val = sum(lng_buf)/len(lng_buf)
    lat_val = sum(lat_buf)/len(lat_buf)
    term.set_attr(0x03)
    term.write('Point: {} (averaged)\n'.format(point_no))
    point_no +=1
    term.set_attr()
    gui_l[2][6] = 'Average'
    term.write('{}, {}\n'.format(spl.lat_minE5, spl.lng_minE5))
    term.write('\n')
    vts.leds(*[0]*12)

term = Terminal(408, 16, 47, 28)

while gnss.init_status():
    pass
try:
    vbox.init(vbox.VBOX_SRC_GNSS_BASIC)
except Exception as e:
    if str(e) == 'VBox source already configured':
        pass
    else:
        raise Exception(e)


gui_l = [
    [gui.PARAM_CLRCOLOR, gui.RGB(255, 255, 255)],
    [gui.CTRL_BUTTON, 16, 16, 376, 220, 32, ['Capture'], capture_cb],
    [gui.CTRL_BUTTON, 16, 248, 376, 220, 32, ['Average'], avg_capture_cb],
    term.gui_list(),]

gui.show(gui_l)
