import uasyncio
import display
import buttons
import mch22
import random
import time
from machine import Pin
from neopixel import NeoPixel

count=0

print("Hello, MCH2022 Badge!")

display.drawFill(display.WHITE)
display.drawText(10, 10, "Hello, MCH2022 badgePython!", display.MAGENTA, "roboto_regular18")
display.flush()

def on_action_b_btn(pressed):
    if pressed:
        show_counter(-1)

def on_action_a_btn(pressed):
    if pressed:
        show_counter(1)

def show_counter(step):
  global count
  # Cleanup
  display.drawText(10, 60, "Hello, button! ({})".format(count), display.WHITE, "roboto_regular18")
  count=count+step
  # Write
  display.drawText(10, 60, "Hello, button! ({})".format(count), display.BLUE, "roboto_regular18")
  display.flush()
  
def reboot(pressed):
  if pressed:
    mch22.exit_python()

continue_loop_leds = False
async def loop_leds():
  global continue_loop_leds
  print("Loop_Leds: {}".format(continue_loop_leds))

  # Pin 19 controls the power supply to SD card and neopixels
  powerPin = Pin(19, Pin.OUT)
  # Pin 5 is the LED's data line
  dataPin = Pin(5, Pin.OUT)
    
  # create a neopixel object for 5 pixels
  np = NeoPixel(dataPin, 5)
    
  # turn on power to the LEDs
  powerPin.on()
  
  while continue_loop_leds:
    print("Loop_Leds: Looping")
    # set some colors for the pixels (RGB)
    np[0] = np[1] = np[2] = np[3] = np[4] = (0,0,0)
    np[random.randrange(4)] = ( random.randrange(10,250, 10), random.randrange(10,250, 10), random.randrange(10,250, 10) )
    
    # send colors out to LEDs
    np.write()

    await uasyncio.sleep(1)

async def enable_leds(pressed):
  global continue_loop_leds
  
  print("Enable Leds Pressed")
  
  if pressed:
    print(pressed)
    continue_loop_leds = True
    await loop_leds()


async def disable_leds(pressed):
  global continue_loop_leds

  print("Disable Leds Pressed")
  
  if pressed:
    print(pressed)
    continue_loop_leds = False

    # Pin 19 controls the power supply to SD card and neopixels
    powerPin = Pin(19, Pin.OUT)
    powerPin.off()

buttons.attach(buttons.BTN_A, on_action_a_btn)
buttons.attach(buttons.BTN_B, on_action_b_btn)
buttons.attach(buttons.BTN_HOME, reboot)
buttons.attach(buttons.BTN_UP, enable_leds)
buttons.attach(buttons.BTN_DOWN, disable_leds)