var config = "ctdo"
var express = require('express');
var app = express();
var server = require('http').createServer(app), io = require('socket.io').listen(server);
var osc = require('node-osc');
var oscMap = require("./configs/" + config + "/oscMap.json");
var states = require("./configs/" + config + "/states.json");
var fs = require('fs');

var host = process.argv.length > 2 ? process.argv[2] : '195.160.169.33'
var port = process.argv.length > 3 ? process.argv[3] : '9000';
var oscSender = new osc.Client(host, port);
var oscReceiver = new osc.Server(3333, '0.0.0.0');

var artnetclient = require('./node_modules/artnet/lib/artnet_client');
var dmxClient = artnetclient.createClient("195.160.169.15", 6454);



var dmxData = new Array(512);
for(var i=0; i<512;i++) {
  dmxData[i] = 0;
}

server.listen(8081);
app.use(express.static('bootstrap'));

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/configs/' + config + '/index.html');
});

io.sockets.on('connection', function (socket) {

    var address = socket.handshake.address;
    console.log("New connection from " + address.address + ":" + address.port);

    socket.on('oscmessage', function (data) {

        var chan = data.chan;
        var value = data.val;

        // hier noch nicht einkommentieren, das sendet das sofort ins hackcenter
        //oscSender.send(chan, value);
        handleMessage(new Array(chan, value))
       //console.log(address, chan, value);
    });
});

oscReceiver.on("message", function (msg, rinfo) {
    handleMessage(msg)
});

function handleMessage(msg) {
    console.log("Message:");
    console.log(msg);
    var chan = msg[0],
        value = msg[1];

    if(chan == null) return;
    // sync states array with value
    if(value == null) {
        if(states[chan] == null) {
            states[chan] = 1
        } else if(states[chan] == 1) {
            states[chan] = 0;
        } else if(states[chan] == 0) {
            states[chan] = 1;
        }
        value = states[chan];
    } else {
       states[chan] = value;
    }

    // get mapped dmx channel
    if(oscMap[chan] != null) {
        dmxData[oscMap[chan]-1] = Math.round(value*255);
        console.log(Math.round(value*255));
        dmxClient.send(dmxData);
    }
    // update osc devices to show the current state
    // to be done in extra function (with whole states array?)
    updateDevices();
    fs.writeFile("./configs/" + config + "/states.json", JSON.stringify(states, null, 4));
}
function updateDevices() {
    for(var chan in states) {
        oscSender.send(chan, states[chan]);
        console.log(chan);
    }
}
