import urequests
import json
import badge
import wifi
import binascii
import machine

def gamma(x, gamma, max_in, max_out):
    print("I:",x)
    r = int(pow(float(x)/float(max_in), gamma) * max_out + 0.5)
    if r < 0:
        r = 0
    if r > 255:
        r = 255
    return r

def hex_to_grbw_list(hex_str):
    global cheerlightsEnabled
    r,g,b = binascii.unhexlify(hex_str)
    w = 0
    g = gamma(g*1.1, 2.8, 255, 255)
    r = gamma(r,     2.8, 255, 255)
    b = gamma(b,     2.8, 255, 255)
    if r == g and g == b and b == 255:
        r,g,b = 0, 0, 0
        w = 255
    return [g, r, b, w]

next_update = None

def update():
    global cheerlightsEnabled
    global next_update

    t = machine.RTC().datetime()
    next_update = (t[0], t[1], t[2], t[3], t[4], t[5], t[6]+30, t[7])

    r = urequests.get("http://api.thingspeak.com/channels/1417/field/2/last.json")
    data = json.loads(r.text)
    print("Cheerlights data: %s" % data)
    vals = hex_to_grbw_list(data['field2'][1:])
    return vals

last_color = [0,0,0,0]
next_color = [0,0,0,0]

def setup():
    global next_color
    global cheerlightsEnabled

    cheerlightsEnabled = int(badge.nvs_get_str('cheerlights', 'state', '0'))
    if (cheerlightsEnabled<1):
        print("Cheerlights: Disabled! Please enable in the app!")
    else:
        badge.leds_enable()
        test()
        wifi.init()
        badge.leds_send_data(bytes(6*([0]*4)), 24)
        next_color = update()

def flatten(l):
    return [item for sublist in l for item in sublist]

def test():
    white = hex_to_grbw_list("ffffff")
    yellow = hex_to_grbw_list("fffc0b")
    green = hex_to_grbw_list("5bff0b")
    orange = hex_to_grbw_list("ffb70b")
    red = hex_to_grbw_list("ff0b50")
    blue = hex_to_grbw_list("330bff")
    badge.leds_send_data(bytes(white+yellow+green+orange+red+blue), 24)
    import time
    time.sleep(1)

# Thanks to https://stackoverflow.com/questions/28015400/how-to-fade-color for the tip
def lerp(a, b, t):
    return a*(1 - t) + b*t
i = 0

def loop(sleepCount):
    global cheerlightsEnabled
    global next_update
    global last_color
    global next_color
    global i
    if cheerlightsEnabled:
        if machine.RTC().datetime() >= next_update:
            next_color = update()
        last_color = list(int(lerp(c, w, 0.01)) for c, w in zip(last_color, next_color))
        badge.leds_send_data(bytes(6*last_color), 24)
    return False
  
def draw(x,y):
    # Not drawing anything
    return 0