var DmxLightManager = function() {
    var lightCount = 24;
    var host = "valot.party";
    var port = "9910";
    var socket = new WebSocket("ws://"+host+":"+port);

    var timeout = undefined;
    var headerLength = 1 + 5;
    var data = new Uint8Array(headerLength + 6 * lightCount);

    data[0] = 1;
    data[1] = 0; 
    data[2] = 68; // D
    data[3] = 75; // K
    data[4] = 68; // D
    data[5] = 0; 

    socket.onclose = function (event) {
        console.log("Socket closed! ", event);
    };
    socket.onerror = function (event) {
        console.log("Socket error! ", event);
    };
    socket.onopen = function (event) {
        console.log("Socket connected!");
    };

    var play = function(){
        if (socket === undefined) {
            console.log("No socket, won't play lights");
            return;
        }

        var lights = [
            {"r":0xFF, "g":0xFF, "b":0xFF},
            {"r":0x00, "g":0xFF, "b":0xFF},
            {"r":0xFF, "g":0x00, "b":0xFF}
        ];


        var ambient = TDEMO.SYNC.getFadeColor();
        var f = TDEMO.SYNC.getFadeValue();
        var group = TDEMO.SYNC.getFadeGroup();

        for(var i = 0; i < lightCount; ++i) {

            var p = headerLength + 6 * i; 
            data[p + 0] = 1;
            data[p + 1] = i;
            data[p + 2] = 0;

            if(i > 21){
                data[p + 3] = Math.floor(ambient.x);
                data[p + 4] = Math.floor(ambient.y);
                data[p + 5] = Math.floor(ambient.z);
            }
            else{
                var l = lights[0];

                if(i % 3 === 0){
                    l = lights[1];
                }
                else if(i % 2 === 0){
                    l = lights[2];
                }

                var fmod = 0.0;
                if(i % group === 0 || group === 4){
                    fmod = 1.0;
                }

                data[p + 3] = Math.floor(l.r*f*fmod);
                data[p + 4] = Math.floor(l.g*f*fmod);
                data[p + 5] = Math.floor(l.b*f*fmod);
            }
        }
        if (socket.readyState == 1) {
            socket.send(data);
        }
    };

    return play;
};