from PIL import ImageGrab
from PIL import Image
from time import sleep
import sys
import json
import requests


api_key = 'YOUR API KEY'

bloom = 'http://BRIDGE_IP/api/API_KEY/lights/LIGHT_NUMBER/state/'

turn_on = json.dumps({'on': True})

requests.put(bloom, turn_on)

if len(sys.argv) == 1:
    accuracy = 20
else:
    accuracy = int(sys.argv[1])


def update_bloom(old_color, new_color):
    r1,g1,b1 = old_color
    r2,g2,b2 = new_color

    if abs(r2-r1) > accuracy or abs(g2-g1) > accuracy or abs(b2-b1) > accuracy:
        red = float(r2/255)
        green = float(g2/255)
        blue = float(b2/255)

        # Apply gamma correction
        red = pow((red + 0.055) / (1.0 + 0.055), 2.4) if (red > 0.04045) else (red / 12.92)
        green = pow((green + 0.055) / (1.0 + 0.055), 2.4) if (green > 0.04045) else (green / 12.92)
        blue = pow((blue + 0.055) / (1.0 + 0.055), 2.4) if (blue > 0.04045) else (blue / 12.92)

        # Convert RGB to XYZ (Using Wide RGB D65 formula)
        X = red * 0.664511 + green * 0.154324 + blue * 0.162028 # Red parity
        Y = red * 0.283881 + green * 0.668433 + blue * 0.047685 # Green Parity
        Z = red * 0.000088 + green * 0.072310 + blue * 0.986039 # Blue parity

        try:
            x = X / (X + Y + Z)
            y = Y / (X + Y + Z)
        
        except ZeroDivisionError:
            pass

        data = json.dumps({'xy': (x,y)})

        requests.put(bloom, data)



def get_avg_color(img):
    width, height = img.size

    pixel_count = width*height

    r_total = 0
    g_total = 0
    b_total = 0

    for x in range(0, width):
        for y in range(0, height):
            r, g, b = img.getpixel((x,y))

            r_total += r
            g_total += g
            b_total += b

    return (int(r_total/pixel_count), int(g_total/pixel_count), int(b_total/pixel_count))

def main():

    avg_color = (0,0,0)

    while(True):
        img = ImageGrab.grab()
        img = img.resize((2,2), Image.ANTIALIAS)

        old_avg = avg_color

        avg_color = get_avg_color(img)

        # print (avg_color)

        update_bloom(old_avg, avg_color)

        sleep(0.2)


if __name__ == '__main__':
    main()