import display
import leds
import color
import utime
import buttons
import os

beercount = 0

def set_leds():
    global beercount
    leds.set_all([color.BLACK] * 15)

    color_display = color.WHITE
    if beercount <= 11:
        color_display = color.GREEN
    elif beercount <= 22:
        color_display = color.YELLOW
    else:
        color_display = color.RED
    
    leds_on_cnt = beercount % 11
    
    if leds_on_cnt == 0 and beercount != 0:
        leds.set_all([color_display] * 11)
    else:
        for i in range(leds_on_cnt):
            leds.set(11-i-1, color_display)

def display_count():
    global beercount
    with display.open() as d:
        d.rect(0, 0, 160, 80, col=color.BLACK)
        d.print("Beer: " + str(beercount), posx=30, posy=25)
        d.update()
    set_leds()

def check_button():
    global beercount
    pressed = buttons.read(
        buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT
    )
    if pressed & buttons.BOTTOM_LEFT != 0:
        beercount -= 1
        display_count()
    if pressed & buttons.BOTTOM_RIGHT != 0:
        beercount += 1
        display_count()

def main():
    display_count()
    while True:
        utime.sleep_ms(200)
        check_button()



if __name__ == "__main__":
    main()
