# import os
# import sys
import time
from time import sleep
# import datetime
import random
import asyncio
from machine import Pin


# settings

led_board = Pin(25, Pin.OUT)
btn_red = Pin(14, Pin.IN, Pin.PULL_UP)
btn_yel = Pin(15, Pin.IN, Pin.PULL_UP)
led_red = Pin(5, Pin.OUT, value=1)
led_yel = Pin(6, Pin.OUT, value=1)
sleep(2)
led_red.off()
led_yel.off()

output_f = 'console'
# output_f = 'log.txt'
"""
NB!
When having this code as (or imported in) "main.py" on Raspberry Pi PICO, the previous line 
gives the name of the file (e.g. 'log.txt') to which the 'logtexts' will be written.
This line could be commented-out in case the code is run from MacBooks 'Thonny'. Then the
'logtexts' will be written to the console (Thonny's shell).
See 'def logtext()' beneath. 
"""

# Prepare log.txt with empty textline:
if output_f != 'console':
    with open(output_f, 'a', encoding='utf-8') as ff:
        ff.write("\n")


# Prepare writing to log.txt or printing to console
def logtext(output_string, end_string="\n"):
    """See comment above"""
    yy, ym, md, hh, mm, ss, wd, yd = time.localtime()
    if output_f != 'console':
        with open(output_f, 'a', encoding='utf-8') as f:
            f.write(f"{yy:04}/{ym:02}/{md:02}  {hh:02}:{mm:02}:{ss:02}: "
                    + output_string + end_string)
    else:
        print(f"{yy:04}/{ym:02}/{md:02}  {hh:02}:{mm:02}:{ss:02}: "
              + output_string, end=end_string)


# Coroutine: blink on a timer
async def blink(led, interval_ms):
    # delay_ms = 0
    while True:
        led.toggle()
        await asyncio.sleep_ms(interval_ms)


# Coroutine: only return on button press
async def wait_button(btn):
    btn_prev = btn.value()
    while btn.value() == 1 or btn.value() == btn_prev:
        btn_prev = btn.value()
        await asyncio.sleep(0.04)


# Coroutine: connect to server and get data
async def prod_rndm_nmbrs():
    nbr_smt1 = float(random.randint(50, 300) / 100)
    nbr_grt10 = random.randint(10, 100)
    data_list = [nbr_smt1, nbr_grt10]
    await asyncio.sleep(0.01)
    # logtext(f"nbr_smt1 = {data_list[0]:4.2f} and nbr_grt10 = {data_list[1]}")

    #     pico_led.on()
    #     sleep(0.1)
    #     pico_led.off()
    #     sleep(0.1)
    #
    # logtext("About to close the connection")
    # writer.close()
    # await writer.wait_closed()

    return data_list


async def main():
    count = 0
    print(f'Push YELLOW button to start proces ...')
    await wait_button(btn_yel)
    asyncio.create_task(blink(led_yel, 500))
    # await asyncio.sleep(0.1)
    print("Push RED button to get random numbers ...")
    while True:
        await wait_button(btn_red)
        led_red(1)
        await asyncio.sleep(0.1)
        led_red(0)
        count += 1
        t1 = time.ticks_ms()
        tsk1 = asyncio.create_task(prod_rndm_nmbrs())
        await asyncio.sleep(0.1)
        result_nbrs = await tsk1
        text = f"[{result_nbrs[0]:4.2f}, {result_nbrs[1]}]"
        logtext(f"{count:4.0}. Result: {text} took {time.ticks_ms() - t1:5.0} ms")
        # sleep(0.01)


#    await wait_button(btn_1)


# sleep(3)
# oled.fill(0) # Clear the display before exiting program.
# oled.show()
# sleep(0.1)

try:
    asyncio.run(main())
except KeyboardInterrupt:
    led_red(0)
    led_yel(0)
    print("Stopped by KBI")
# print(data_list)