import badge, appglue, ugfx, easydraw, time
import wifi
import urequests as requests
from random import randint

#[["1550256576", "Hacker Bart", "Fritz Limo"], 
# ["1550256672", "ijskimo", "Club Mate"], 
# ["1550257450", "atdt112", "Club Mate Winter"], ["1550260192", "relocker", "Club Mate"], ["1550265195", "Hacker Bart", "Fritz Limo"], ["1550265452", "pocketm\u0113ch", "Club Mate"], ["1550265990", "Anonymous", "Club Mate"], ["1550268110", "chocolight", "Club Mate Winter"], ["1550268186", "rickgeex", "Club Mate Winter"], ["1550268488", "herr lord anpnymous ", "Club Mate"], ["1550268987", "whiteangels", "Fritz Cola"], ["1550269159", "Hoi", "Club Mate"], ["1550270306", "Micius", "Fritz Cola"], ["1550271483", "Spero", "Fritz Cola"], ["1550272006", "renze", "Club Mate"], ["1550272278", "tttuhgfhu", "Fritz Cola"], ["1550273220", "Hacker Bart", "Fritz Limo"], ["1550273855", "Anonymous", "Fritz Cola"], ["1550278452", "Test", "Club Mate Winter"], ["1550278467", "Test", "Club Mate Winter"], ["1550312659", "Anonymous", "Club Mate"], ["1550313048", "hax4life", "Club Mate Ice-T"], ["1550313290", "I'm a \ud83e\udd84", "Fritz Cola"], ["1550313528", "rick", "Club Mate Winter"], ["1550313585", "dennus", "Club Mate Ice-T"], ["1550313996", "chocolight", "Club Mate Winter"], ["1550315101", "SynQ", "Club Mate"], ["1550315175", "Dapperedodo", "Fritz Cola"], ["1550315701", "Hacker Bart", "Fritz Limo"], ["1550315969", "Henri\u00ebtte \u00c4cker", "Club Mate"], ["1550315986", "\ud83c\udf7a", "Fritz Cola"], ["1550317875", "Tijme", "Club Mate"], ["1550318004", "kinroy", "Club Mate Ice-T"], ["1550318034", "qguv", "Club Mate"], ["1550318080", "bobby tables", "Club Mate Ice-T"], ["1550318141", "Dmitrijus", "Club Mate Ice-T"], ["1550318188", "Takkedinges", "Club Mate"], ["1550318246", "TDvenlo - MPG", "Fritz Cola"]]
url = "https://automate.nwlab.nl/api/log"

def process_entries(data):
    total_drinks = {"Fritz Limo": 0, "Fritz Cola": 0, "Club Mate": 0, "Club Mate Ice-T": 0, "Club Mate Winter": 0}
    cur_time = int(time.time())
    last_vend = ["0", "nobody", "drink"]
    vends_last_four_hours = 0

    for entry in data:
        total_drinks[entry[2]] += 1
        if int(entry[0]) > int(last_vend[0]):
            last_vend[0] = entry[0]
            last_vend[1] = entry[1]
            last_vend[2] = entry[2]

        if int(entry[0]) > cur_time - 60*60 * 4:
            vends_last_four_hours += 1

    return {"total_drinks": total_drinks, "last_vend": last_vend, "last_four_hours": vends_last_four_hours}


def get_entries():
    try:
      data = requests.get(url)
    except:
        easydraw.msg("Nope, something went wrong")
        time.sleep(2)
        appglue.home()

    return data.json()

def app_main(pressed = True):
    if pressed:
        data = get_entries()
        processed_entries = process_entries(data)
        show_screen(processed_entries)

def clear():
    ugfx.clear(ugfx.BLACK)
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()

def go_home(pressed):
    if pressed:
        appglue.home()

def btn_crazy_colors(pressed):
    if pressed:
        crazy_color_task()

def random_parrot(pressed):
    if pressed:
        draw_random_parrot()

def draw_random_parrot():
        pos_x = randint(0, ugfx.height() - 30)
        pos_y = randint(0, ugfx.width() - 39)
        badge.eink_png(pos_x, pos_y, '/lib/statomate/parrot_small.png')
        ugfx.flush()

def disco_mode(pressed):
    # STOP STEALING MY CODE!!!!!!11!!one!111 disco dave!
    if pressed:
        delay_for = randint(0, 600)
        clear()

        ugfx.set_lut(ugfx.GREYSCALE)
        ugfx.string(40, 25, "PARTYING FOR: ", "Roboto_Regular12", ugfx.BLACK)
        ugfx.string(55, 40, str(delay_for / 10), "Roboto_Regular12", ugfx.BLACK)
        badge.eink_png(ugfx.height() - 70, 10, '/lib/statomate/disco_parrot.png')
        ugfx.flush()

        for i in range(delay_for):
            badge.leds_send_data(bytes(colors()))
            if  i % 15 == 0: 
                draw_random_parrot()
            time.sleep(0.1)    
        badge.leds_disable()
        app_main()

def colors():
    results = []

    for x in range(6):
        primary = randint(1,3)
        one = randint(125 if primary == 1 else 0, 255 if primary == 1 else 75)
        two = randint(125 if primary == 2 else 0, 255 if primary == 2 else 75)
        three = randint(125 if primary == 3 else 0, 255 if primary == 3 else 75)

        results.append(one)
        results.append(two)
        results.append(three)
        results.append(0)

    return results

def crazy_color_task():
    #NW kleuren: 
    # R 75 G 166 B 200
    # R 70 G 89 B 102\

    clr1 = [50, 0, 100, 0]
    clr2 = [0,0,100,0]

    # data[0-3] LED 1
    # 0 R 1 G 2 B 3 Helderheid
    # data[4-7] LED 2
    for i in range(6):
        data = [0]*4*i + clr1 + [0] * 4 * (5-i)
        badge.leds_send_data(bytes(data))
        time.sleep(0.5)
    data = [0]*6*4
    badge.leds_send_data(bytes(data))

def show_screen(data):
    ugfx.init()
    clear()

    #load nw logo at top of screen
    ugfx.set_lut(ugfx.GREYSCALE)    

    badge.eink_png(0,0,'/lib/statomate/nwlogo.png')

    offset = 0
    i = 0
    total = 0
    for key,value in data["total_drinks"].items():
        total += value
        if "Club Mate" in key:
            key = key.replace("Club Mate", "Mate")
        ugfx.string(0, offset + i * 15, key + ": " + str(value), "Roboto_Regular12", ugfx.BLACK)
        i+=1
    
    ugfx.string(0, offset+ i * 15, "Total drinks: " + str(total),  "Roboto_Regular12", ugfx.BLACK )
    i += 1 
    ugfx.thickline(0, offset + i * 15 + 5, ugfx.width() - 25, offset + i * 15 + 5, ugfx.BLACK, 2, 1)
    i += 1
    ugfx.string(0, offset + i * 15, "Last vend went to:", "Roboto_Regular12", ugfx.BLACK)
    i += 1
    ugfx.string(30, offset + i * 15, data["last_vend"][1], "Roboto_Regular12", ugfx.BLACK)
    i  += 1
    ugfx.string(0, offset + i * 15, "Drinks in the last 4 hours:", "Roboto_Regular12", ugfx.BLACK)
    i  += 1
    ugfx.string(30, offset + i * 15, str(data["last_four_hours"]), "Roboto_Regular12", ugfx.BLACK)
    
    # stolen from easydraw.py
    l = ugfx.get_string_width("UP/Start to refresh!", "pixelade13")
    s = ugfx.get_string_width("B/Select to exit", "pixelade13")
    ugfx.string(ugfx.width()-l, ugfx.height()-1*14, "UP/Start to refresh!", "pixelade13", ugfx.BLACK)
    ugfx.string(ugfx.width()-s, ugfx.height()-2*14, "B/Select to exit", "pixelade13", ugfx.BLACK)

    #flipped png so count pixels from the other side of the screen
    badge.eink_png(ugfx.height()-87, 25, '/lib/statomate/parrot.png')
    ugfx.line(0, ugfx.height()-30, ugfx.width(), ugfx.height()-30, ugfx.BLACK)
    ugfx.flush()

ugfx.input_attach(ugfx.BTN_B, go_home)
ugfx.input_attach(ugfx.BTN_SELECT, go_home)
ugfx.input_attach(ugfx.JOY_RIGHT, btn_crazy_colors)
ugfx.input_attach(ugfx.BTN_START, lambda pressed: app_main(pressed))
ugfx.input_attach(ugfx.JOY_UP, lambda pressed: app_main(pressed))
ugfx.input_attach(ugfx.JOY_LEFT, lambda pressed: random_parrot(pressed))
ugfx.input_attach(ugfx.JOY_DOWN, lambda pressed: disco_mode(pressed))

wifi.connect()
if not wifi.wait(30, True):
    easydraw.msg("Nope, no Wi-Fi")
    time.sleep(2)
    appglue.home()

app_main()
