"""
Barometric altimeter

Author: Nubesik
"""
import bme680, utime, display, buttons, ujson, uio
from apps.barometric_altimeter import betterbutton as bb
# docs: https://firmware.card10.badge.events.ccc.de/

BUTTONS = []
LAST_ACTION = 0
CONFIG = {}


def init_buttons():
    global BUTTONS, LAST_ACTION
    LAST_ACTION = utime.time()
    for b in (buttons.BOTTOM_LEFT, buttons.TOP_RIGHT, buttons.BOTTOM_RIGHT):
        BUTTONS.append(bb.Button(b))


def check_buttons():
    global BUTTONS, CONFIG, LAST_ACTION
    for b in BUTTONS:
        b.checkButton()
    if BUTTONS[0].pressed():
        # left
        LAST_ACTION = utime.time()
        CONFIG['cal'] = CONFIG['cal'] - 1
        update_config()
    if BUTTONS[1].pressed():
        # OK
        LAST_ACTION = utime.time()
    if BUTTONS[2].pressed():
        # right
        LAST_ACTION = utime.time()
        CONFIG['cal'] = CONFIG['cal'] + 1
        update_config()


def update_config():
    global CONFIG
    # only absolute path works. why?
    p = '/apps/barometric_altimeter/'
    try:
        f = open(p+'config.json', mode='w')
    except Exception as ex:
        print(ex)
    f.write(ujson.dumps(CONFIG))
    f.close()


def init_config():
    global CONFIG
    # only absolute path works. why?
    p = '/apps/barometric_altimeter/'
    #p = ''
    try:
        f = open(p+'config.json', mode='r')
    except Exception as ex:
        print(ex)
        f = open(p+'config_default.json', mode='r')
    CONFIG = ujson.loads(f.read())
    f.close()


def main():
    global CONFIG
    init_config()
    disp = display.open()
    disp.clear()
    init_buttons()
    while True:
        check_buttons()
        with bme680.Bme680() as environment:
            d = environment.get_data()
            pressure = d.pressure

        height = 288.15/0.0065*(1-(pressure/1013.25)**(1/5.255)) + CONFIG['cal']
        disp.print("Altitude",
                   fg=[255,255,255], bg=[0,0,0], posx=0, posy=0)
        disp.print("{:04.1f} m".format(height),
                   fg=[255,255,255], bg=[0,0,0], posx=0, posy=40)
        disp.update()

        # console output
        print("Temp: {:4.0f}  °C".format(d.temperature))
        print("Humi: {:4.0f} %rh".format(d.humidity))
        print("Pres: {:4.0f} hPa".format(d.pressure))
        print("Alt:  {:4.1f} m".format(height))


main()