#!/usr/bin/env python3

import sacn
import time
import sys
import yaml
import math
import random
from util import fprint
import platform    # For getting the operating system name
import subprocess  # For executing a shell command
from util import win32
import cv2
import numpy as np
from uptime import uptime

sender = None
debug = True
config = None
leds = None
leds_size = None
leds_normalized = None
controllers = None
data = None
start = uptime()

def ping(host):
    #Returns True if host (str) responds to a ping request.

    # Option for the number of packets as a function of
    if win32:
        param1 = '-n'
        param2 = '-w'
        param3 = '250'
    else:
        param1 = '-c'
        param2 = '-W'
        param3 = '0.25'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param1, '1', param2, param3, host]

    return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) == 0

def map():
    global config
    global leds
    global leds_size
    global leds_normalized
    global controllers

    with open('config.yml', 'r') as fileread:
        #global config
        config = yaml.safe_load(fileread)

    leds = list()
    leds_size = list()
    controllers = list()
    #fprint(config["led"]["map"])
    for shape in config["led"]["map"]:
        if shape["type"] == "circle":
            #fprint(shape["pos"])
            anglediv = 360.0 / shape["size"]
            angle = 0
            radius = shape["diameter"] / 2
            lednum = shape["start"]
            if len(leds) < lednum + shape["size"]:
                for x in range(lednum + shape["size"] - len(leds)):
                    leds.append(None)
                    leds_size.append(None)
            while angle < 359.999:
                tmpangle = angle + shape["angle"]
                x = math.cos(tmpangle * (math.pi / 180.0)) * radius + shape["pos"][0]
                y = math.sin(tmpangle * (math.pi / 180.0)) * radius + shape["pos"][1]
                leds[lednum] = (x,y)
                lednum = lednum + 1
                angle = angle + anglediv
        
        elif shape["type"] == "strip":
            angle = shape["angle"]
            lednum = shape["start"]
            length = shape["length"]
            distdiv = length / shape["size"]
            dist = distdiv / 2
            xmov = math.cos(angle * (math.pi / 180.0)) * distdiv
            ymov = math.sin(angle * (math.pi / 180.0)) * distdiv
            pos = shape["pos"]
            if len(leds) < lednum + shape["size"]:
                for x in range(lednum + shape["size"] - len(leds)):
                    leds.append(None)
                    leds_size.append(None)
            
            while dist < length:
                leds[lednum] = (pos[0], pos[1])
                pos[0] += xmov
                pos[1] += ymov
                dist += distdiv
                lednum = lednum + 1


    flag = 0
    for x in leds:
        if x is None:
            flag = flag + 1
    if flag > 0:
        fprint("Warning: Imperfect LED map ordering. Hiding undefined lights.")
        for x in range(len(leds)):
            if leds[x] is None:
                leds[x] = (0, 0)


    #leds = tmpleds.reverse()
    #fprint(leds)

    # controller mapping
    for ctrl in config["led"]["controllers"]:
        if len(controllers) < ctrl["universe"]+1:
            for x in range(ctrl["universe"]+1 - len(controllers)):
                controllers.append(None)

        controllers[ctrl["universe"]] = (ctrl["ledstart"],ctrl["ledend"]+1,ctrl["ip"])
        for x in range(ctrl["ledstart"],ctrl["ledend"]+1):
            leds_size[x] = len(ctrl["mode"])
    #fprint(controllers)
    
    if(debug):
        import matplotlib.pyplot as plt
        plt.axis('equal')
        for ctrl in controllers:
            plt.scatter(*zip(*leds[ctrl[0]:ctrl[1]]), s=2)
        #plt.scatter(*zip(*leds), s=3)
        plt.savefig("map.png", dpi=600, bbox_inches="tight")

    leds_adj = [(x-min([led[0] for led in leds]), # push to zero start
                    y-min([led[1] for led in leds]) )
                   for x, y in leds]
    
    leds_normalized = [(x / max([led[0] for led in leds_adj]), 
                    y / max([led[1] for led in leds_adj]))
                   for x, y in leds_adj]
    #return leds, controllers

def init():
    map()
    global sender
    global config
    global leds
    global leds_size
    global controllers
    global data
    sender = sacn.sACNsender(fps=config["led"]["fps"], universeDiscovery=False)
    sender.start()  # start the sending thread
    for x in range(len(controllers)):
        print("Waiting for the controller at", controllers[x][2], "to be online...", end="")
        count = 0
        while not ping(controllers[x][2]):
            count = count + 1
            if count >= config["led"]["timeout"]:
                fprint(" ERROR: controller still offline after " + str(count) + " seconds, continuing...")
                break
        if count < config["led"]["timeout"]:
            fprint(" done")
    for x in range(len(controllers)):
        print("Activating controller", x, "at", controllers[x][2], "with", controllers[x][1]-controllers[x][0], "LEDs.")
        sender.activate_output(x+1)  # start sending out data
        sender[x+1].destination = controllers[x][2]
    sender.manual_flush = True

    # initialize global pixel data list
    data = list()
    for x in range(len(leds)):
        if leds_size[x] == 3:
            data.append((20,20,127))
        elif leds_size[x] == 4:
            data.append((50,50,255,0))
        else:
            data.append((0,0,0))
    sendall(data)
    #time.sleep(50000)    
    fprint("Running start-up test sequence...")
    for y in range(100):
        for x in range(len(leds)):
            setpixel(0,0,150,x)
        sendall(data)
        #time.sleep(2)
        #alloffsmooth()

def sendall(datain):
    # send all LED data to all controllers
    # data must have all LED data in it as [(R,G,B,)] tuples in an array, 1 tuple per pixel
    global controllers
    global sender
    sender.manual_flush = True
    for x in range(len(controllers)):
        sender[x+1].dmx_data = list(sum(datain[controllers[x][0]:controllers[x][1]] , ())) # flatten the subsection of the data array
    
    sender.flush()
    time.sleep(0.002)
    #sender.flush() # 100% reliable with 2 flushes, often fails with 1
    #time.sleep(0.002)
    #sender.flush()

def fastsendall(datain):
    # send all LED data to all controllers
    # data must have all LED data in it as [(R,G,B,)] tuples in an array, 1 tuple per pixel
    global controllers
    global sender
    sender.manual_flush = False
    print(datain[controllers[0][0]:controllers[0][1]])
    for x in range(len(controllers)):
        sender[x+1].dmx_data = list(sum(datain[controllers[x][0]:controllers[x][1]] , ())) # flatten the subsection of the data array
    
    sender.flush()

def senduniverse(datain, lednum):
    # send all LED data for 1 controller/universe
    # data must have all LED data in it as [(R,G,B,)] tuples in an array, 1 tuple per pixel
    global controllers
    global sender
    for x in range(len(controllers)):
        if lednum >= controllers[x][0] and lednum < controllers[x][1]:
            sender[x+1].dmx_data = list(sum(datain[controllers[x][0]:controllers[x][1]] , ())) # flatten the subsection of the data array
    
    sender.flush()
    time.sleep(0.004)
    #sender.flush() # 100% reliable with 2 flushes, often fails with 1
    #time.sleep(0.002)
    #sender.flush()

def alloff():
    tmpdata = list()
    for x in range(len(leds)):
        if leds_size[x] == 3:
            tmpdata.append((0,0,0))
        elif leds_size[x] == 4:
            tmpdata.append((0,0,0,0))
        else:
            tmpdata.append((0,0,0))
    sendall(tmpdata)
    #sendall(tmpdata)
    #sendall(tmpdata) #definitely make sure it's off

def allon():
    global data
    sendall(data)

def alloffsmooth():
    tmpdata = data
    for x in range(256):
        for x in range(len(data)):
            setpixel(tmpdata[x][0]-1,tmpdata[x][1]-1,tmpdata[x][2]-1, x)
        sendall(tmpdata)

    alloff()

def setpixelnow(r, g, b, num):
    # slight optimization: send only changed universe
    # unfortunately no way to manual flush data packets to only 1 controller with this sACN library
    global data
    setpixel(r,g,b,num)
    senduniverse(data, num)

def setpixel(r, g, b, num):
    global data
    global leds_size
    # constrain values
    if r < 0:
        r = 0
    elif r > 255:
        r = 255
    if g < 0:
        g = 0
    elif g > 255:
        g = 255
    if b < 0:
        b = 0
    elif b > 255:
        b = 255

    if leds_size[num] == 3:
        data[num] = (int(r), int(g), int(b))
    elif leds_size[num] == 4: # cut out matching white and turn on white pixel instead
        data[num] = (( int(r) - int(min(r,g,b)), int(g) - int(min(r,g,b)), int(b) - int(min(r,g,b)), int(min(r,g,b))) )
    else:
        data[num] = (int(r), int(g), int(b))
    

def close():
    global sender
    time.sleep(0.5)
    sender.stop()

def mapimage(image, fps=90):
    global start
    while uptime() - start < 1/fps:
        time.sleep(0.00001)
    fprint(1 / (uptime() - start))
    start = uptime()
    minsize = min(image.shape[0:2])
    leds_normalized2 = [(x * minsize, 
                        y * minsize)
                        for x, y in leds_normalized]
    
    cv2.imshow("video", image)
    cv2.waitKey(1)

    
    #im_rgb = image #cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # OpenCV uses BGR format by default
    avgx = 0
    avgy = 0
    for xx in range(len(leds_normalized2)):
        led = leds_normalized2[xx]
        x, y = int(round(led[0])), int(round(led[1]))
        
        if x < image.shape[1] and y < image.shape[0]:
            #avgx += x
            #avgy += y
            color = tuple(image[y, x])
            setpixel(color[2]/2,color[1]/2,color[0]/2,xx) # swap b & r
            #print(color)
        else:
            #avgx += x
            #avgy += y
            setpixel(0,0,0,xx)
    #avgx /= len(leds)
    #avgy /= len(leds)
    #print((avgx,avgy, max([led[0] for led in leds_adj]), max([led[1] for led in leds_adj]) , min(image.shape[0:2]) ))
    global data
    fastsendall(data)

    
if __name__ == "__main__":
    init()
    cap = cv2.VideoCapture('output.mp4')
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        mapimage(frame)

    time.sleep(1)
    close()
    #sys.exit(0)