import machine, time, random
import groveLCD as lcd

global count
count=0

def updateDisplay():
    lcd.setText_norefresh("Number of stamps\n       %d" %count)
    
lcd.setRGB(50,0,50)
lcd.clearText()
lcd.setText_norefresh("Hello Marcus!")
time.sleep(2)
updateDisplay()

btnP=machine.Pin(15,machine.Pin.IN,machine.Pin.PULL_UP)
btnD=machine.Pin(16,machine.Pin.IN,machine.Pin.PULL_UP)

global btnP_pressed
btnP_pressed=False

global btnD_pressed
btnD_pressed=False

# button handlers (interrupts)
def btn_reader(pin):
    btn=pin
    while True:
        if btnP.value()==0:
            btnP_pressed=True
            increment()
            time.sleep(0.5)
            btnP_pressed=False
        elif btnD.value()==0:
            btnD_pressed=True
            decrement()
            time.sleep(0.5)
            btnD_pressed=False
    
def increment():
    global count
    count+=1
    global r
    global g
    global b
    r=0
    g=0
    b=0
    def setR():
        global r
        r=random.randrange(50)
        return r
    def setG():
        global g
        g=random.randrange(50)
        return g
    def setB():
        b=random.randrange(50)
        return b
    if (count%10)==0:
        setR();setG();setB()
        lcd.setRGB(r,g,b)
        lcd.setText("Good Job Marcus!\n Pick a prize")
        time.sleep(3)
        lcd.setRGB(50,0,50)
    updateDisplay()
    return count
    
def decrement():
    global count
    count-=1
    updateDisplay()
    return count

btnP.irq(trigger=machine.Pin.IRQ_FALLING,handler=btn_reader(btnP))
btnD.irq(trigger=machine.Pin.IRQ_FALLING,handler=btn_reader(btnD))

# TODO put special surprise if reach "full" board <66>