var rf24 = require('./build/Release/nrf24Node.node');
//var http = require('http').createServer(handler);
var mysql= require('mysql');
var io = require('socket.io')(90);
var jsonfile = require('jsonfile');
fs = require('fs');
var async = require('async');

// nacitanie zariadeni zo suboru
var file = '/home/pi/devices.json';
var obj = jsonfile.readFileSync(file);

// Planovane aktivity
var schedule = require('node-schedule');

// VIDEO
global.video_on = 0;
global.video_pid = 0;
var spawn=require('child_process').spawn
, child=null;
// VIDEO END

// ulozenie zariadeni do pamate
var device = [];
for(var i in obj.devices){
	device[obj.devices[i].type] = obj.devices[i];
}

// nastavenie DB
var connection = mysql.createConnection({
	host     : 'localhost',
	user     : 'root',
	password : 'root',
	database : 'server'
});



var file = '/home/pi/settings.json';
var settings = jsonfile.readFileSync(file);
io.sockets.on('connection', function (socket) {


  // VYPIS VOLNYCH MODULOV
  socket.on('unused_devices', function (data, res) {
  	connection.query('SELECT `id`, `type` FROM `devices` WHERE  `active` = "0"', function (error, results, fields) {
  		var response = {};
  		response.results = [];
  		for(var i in results){
  			response.results[i] = {};

  			response.results[i].id = results[i].id;
  			if(typeof device[results[0].type] != 'undefined') {
  				response.results[i].name = device[results[i].type].name;
  			} else {
  				response.results[i].name = "Neznáme zariadenie";
  			}
  		}
  		response.status = 1;
  		res(response);
  	});
  });

  // VYPIS PRIHLASENYCH MODULOV
  socket.on('used_devices', function (data, res) {
  	connection.query('SELECT `id`, `type` FROM `devices` WHERE  `active` = "1"', function (error, results, fields) {
  		var response = {};
  		response.results = [];
  		for(var i in results){
  			response.results[i] = {};

  			response.results[i].id = results[i].id;
  			if(typeof device[results[0].type] != 'undefined') {
  				response.results[i].name = device[results[i].type].name;
  			} else {
  				response.results[i].name = "Neznáme zariadenie";
  			}
  		}
  		response.status = 1;
  		res(response);
  	});
  });

  // PRIHLASENIE VOLNEHO MODULU
  socket.on('add_device', function (data, res) {
  	connection.query('SELECT `id`, `code`, `hash`, `type` FROM `devices` WHERE  `id` = "'+data.id+'"', function (error, results, fields) {
  		var response = {};
  		if(results.length == 1) {
  			if(typeof device[results[0].type] != 'undefined') {

  				var rx = "";
  				if(settings.rx < 16) {
  					rx = "0"+settings.rx.toString(16);
  				} else {
  					rx = settings.rx.toString(16);
  				}

  				var tx = "";
  				if(settings.tx < 16) {
  					tx = "0"+settings.tx.toString(16);
  				} else {
  					tx = settings.tx.toString(16);
  				}

  				var send = false;

  				if(results[0].code == 0) {
  					new_module_id(function(err, code) {
  						console.log(code);
  						console.log("callback je tu");
  						connection.query('UPDATE `devices` SET `code` = "'+code+'" WHERE `id` = "'+results[0].id+'";', function (error, results, fields) {});
  						send = rf24.send_data(code, results[0].hash+" "+tx+rx, 0x05, 15);
  					});
  				} else {
  					console.log(results[0].code);
  					send = rf24.send_data(results[0].code, results[0].hash+" "+tx+rx, 0x05, 15);

  				}
  				if(send.status) {
  					console.log("ok");
  					connection.query('UPDATE `devices` SET `active` = "1" WHERE  `id` = "'+data.id+'"', function (error, results, fields) {
  						if (error) throw error;
  					});

  					for(var i in device[results[0].type].outputs) {
  						connection.query('INSERT INTO `outputs` (`id`, `device`, `name`, `output_name`, `room`, `type`, `min_value`, `max_value`, `byte`, `length`, `value`) VALUES (NULL, "'+results[0].id+'", "'+device[results[0].type].outputs[i].name+'", "'+device[results[0].type].outputs[i].name+'", "0", "'+device[results[0].type].outputs[i].type+'", "'+device[results[0].type].outputs[i].min_value+'", "'+device[results[0].type].outputs[i].max_value+'", "'+device[results[0].type].outputs[i].byte+'", "0", "'+device[results[0].type].outputs[i].min_value+'");', function (error, results, fields) {
  							if (error) throw error;
  						});
  					}

  					for(var i in device[results[0].type].sensors) {
  						connection.query('INSERT INTO `sensors` (`id`, `device`, `name`, `sensor_name`, `room`, `color`, `type`, `unit`, `value_type`, `byte`, `length`) VALUES (NULL, "'+results[0].id+'", "'+device[results[0].type].sensors[i].name+'", "'+device[results[0].type].sensors[i].name+'", "0", "0", "'+device[results[0].type].sensors[i].type+'", "'+device[results[0].type].sensors[i].unit+'", "'+device[results[0].type].sensors[i].value_type+'", "'+device[results[0].type].sensors[i].byte+'", "'+device[results[0].type].sensors[i].length+'");', function (error, results, fields) {
  							if (error) throw error;
  						});
  					}

  					response.status = 1;
  				} else {
  					console.log("neok");
  					response.status = 0;
  					response.error = "Modul nedostupný";
  				}
  			} else {
  				response.status = 0;
  				response.error = "Neznámy typ modulu";
  			}
  		} else {
  			response.status = 0;
  			response.error = "Neznámy modul (chyba)";
  		}
  		res(response);
  	});
  });

  // VYMAZANIE ULOZENEHO MODULU

  socket.on('delete_device', function (data, res) {
  	async.waterfall([
  		function(callback) {
  			connection.query('DELETE FROM `devices` WHERE `id` = "'+data.id+'";', function (error, results, fields) {
  				callback(null);
  			});
  		},
  		function(callback) {  /// skontrolovat
  			connection.query('DELETE FROM `events` LEFT JOIN `outputs` ON `events`.`output` = `outputs`.`id` WHERE `outputs`.`device` = "'+data.id+'";', function (error, results, fields) {
  				callback(null);
  			});
  		},
  		function(callback) {
  			connection.query('DELETE FROM `termostats` LEFT JOIN `outputs` ON `termostats`.`output` = `outputs`.`id` WHERE `outputs`.`device` = "'+data.id+'";', function (error, results, fields) {
  				callback(null);
  			});
  		},
  		function(callback) {
  			connection.query('DELETE FROM `outputs` WHERE `device` = "'+data.id+'";', function (error, results, fields) {
  				callback(null);
  			});
  		},
  		function(callback) {
  			connection.query('DELETE FROM `events` LEFT JOIN `sensors` ON `events`.`sensor` = `sensors`.`id` WHERE `sensors`.`device` = "'+data.id+'";', function (error, results, fields) {
  				callback(null);
  			});
  		},
  		function(callback) {
  			connection.query('DELETE FROM `sensors` WHERE `device` = "'+data.id+'";', function (error, results, fields) {
  				callback(null);
  			});
  		}], function(err) {
  			var response = {};
  			response.status = 1;
  			res(response);
  		});
  });


  // VYPIS IZIEB

  socket.on('list_rooms', function (data, res) {
  	connection.query('SELECT *, (SELECT `sensors_short_record`.`value` FROM `sensors_short_record` WHERE `sensors_short_record`.`sensor`=`rooms`.`temp` ORDER BY `sensors_short_record`.`id` DESC LIMIT 1) AS value FROM `rooms`', function (error, results, fields) {
  		console.log(results);
  		if (error) throw error;
  		var response = {};
  		response.results = [];
  		for(var i in results){
  			response.results[i] = {};
  			response.results[i].id = results[i].id;
  			response.results[i].name = results[i].name;
  			response.results[i].temp = results[i].temp;
  			response.results[i].temp_value = results[i].value;

  		}
  		response.status = 1;
  		res(response);
  	});
  });

  // PRIDANIE IZBY

  socket.on('add_room', function (data, res) {
  	connection.query('INSERT INTO `rooms` (`id`, `img`, `name`, `temp`, `termostat`) VALUES (NULL, "", "'+data.name+'", "", "");', function (error, results, fields) {
  		if (error) throw error;
  		var response = {};

  		response.status = 1;
  		response.new_room_id = results.insertId
  		res(response);
  	});
  });

  // ZMAZANIE IZBY

  // VYPIS OBSAHU IZBY
  socket.on('show_room', function (data, res) {
  	async.waterfall([
  		function(callback) {
  			var response = {};
  			response.results = {};
  			connection.query('SELECT *, (SELECT `termostats`.`temp` FROM `termostats` WHERE `termostats`.`output`=`outputs`.`id`) as temp FROM `outputs` WHERE `room` = "'+data.room_id+'"', function (error, results, fields) {
  				response.results.outputs = results;
  				callback(null, response);
  			});

  		}, function(response, callback) {
  			connection.query('SELECT *, (SELECT `sensors_short_record`.`value` FROM `sensors_short_record` WHERE `sensors_short_record`.`sensor`=`sensors`.`id` AND `sensors_short_record`.`status`=1 LIMIT 1) AS value, (SELECT `sensors_short_record`.`time` FROM `sensors_short_record` WHERE `sensors_short_record`.`sensor`=`sensors`.`id` AND `sensors_short_record`.`status`=1 LIMIT 1) AS time FROM `sensors` WHERE `room` = "'+data.room_id+'"', function (error, results, fields) {
  				for(var i in results){
		  			if(results[i].type == "push") {
		  				results[i].value = Math.floor(Date.now() / 1000) - results[i].time;
		  			}
		  		}
		  		console.log(results);

  				response.results.sensors = results;
  				callback(null, response);
  			});

  		}, function(response, callback) {
  			connection.query('SELECT * FROM `events` WHERE `room` = "'+data.room_id+'"', function (error, results, fields) {
  				response.results.events = results;
  				callback(null, response);
  			});

  		}], function(err, response) {
  			response.status = 1;
  			console.log(response);
  			res(response);
  		}

  		);
  });

  // VYPIS NEPOUZIVANYCH SENSORS

  socket.on('show_unused_sensors', function (data, res) {
  	connection.query('SELECT * FROM `sensors` WHERE `room` = "0"', function (error, results, fields) {
  		console.log(results);
  		var response = {};
  		response.results = {};
  		response.results.sensors = [];

  		response.results.sensors = results;

  		response.status = 1;
  		res(response);
  	});
  });

  // VYPIS NEPOUZIVANYCH OUTPUTS

  socket.on('show_unused_outputs', function (data, res) {
  	connection.query('SELECT * FROM `outputs` WHERE `room` = "0"', function (error, results, fields) {
  		console.log(results);
  		var response = {};
  		response.results = {};
  		response.results.outputs = [];
  		response.results.outputs = results;

  		response.status = 1;
  		res(response);
  	});
  });

  // PRIRADENIE SENSOR DO IZBY

  socket.on('assign_sensor', function (data, res) {
  	console.log("data id: "+data.id)
  	connection.query('UPDATE `sensors` SET `name` = "'+data.name+'", `room` = "'+data.room+'", `color` = "'+data.color+'"  WHERE `id` = "'+data.id+'";', function (error, results, fields) {
  		console.log(results);
  		var response = {};
  		response.status = 1;
  		res(response);
  	});
  });

  // PRIRADENIE OUTPUT DO IZBY

  socket.on('assign_output', function (data, res) {
  	connection.query('UPDATE `outputs` SET `name` = "'+data.name+'", `room` = "'+data.room+'" WHERE `id` = "'+data.id+'";', function (error, results, fields) {
  		console.log(results);
  		var response = {};
  		response.status = 1;
  		res(response);
  	});
  });

  // VYTVORENIE EVENTU

  socket.on('add_event', function (data, res) {


  	connection.query('INSERT INTO `events` (`id`, `name`, `room`, `type`, `sensor`, `start`, `stop`, `timeout`, `days`, `event_on`, `output`, `value`, `active`) VALUES (NULL, "'+data.name+'", "'+data.room+'", "'+data.type+'", "'+data.sensor+'", "'+data.start+'", "'+data.stop+'", "'+data.timeout+'", "'+data.days+'", "'+data.event_on+'", "'+data.output+'", "'+data.value+'", 1);', function (error, results, fields) {
  		if (error) throw error;
  		var response = {};

  		if(data.type = "time") {
  			var time = data.start.split(":");
  			var id = results.insertId;

  			var job = schedule.scheduleJob(time[1] + ' ' + time[0] + ' * * ' + data.days, function() {
  				async.waterfall([
  					function(callback) {
  						connection.query('SELECT `output`, `value`, `active` FROM `events` WHERE  `id` = ' + id, function (error, results, fields) {
  							var info = {};
  							if(results.length == 1) {
  								if(results[0].active == 1) {
  									info.status = 1;
  									info.output = results[0].output;
  									info.value = results[0].value;
  									callback(null, info);
  								} else {
  									callback('noactive', info);
  								}
  							} else {
  								callback('zero', info);
  							}

  						});

  					}, function(info, callback) {
  						if(info.status == 1) {
  							connection.query('SELECT * FROM `outputs` WHERE `id` = ' + info.output , function (error, results, fields) {
  								var output = Object.assign({},results[0]);
  								var value = info.value;
  								callback(null, output, value);
  							});
  						} else {

  						}
  					}, function(output, value, callback) {
  						changeValue(output, value, function(err, result) {
  							callback(null, result);
  						});

  					}], function(err, result) {
  						if(err == 'noactive') {
  							// event je neaktivny
  						} else if(err == 'zero') {
  							job.cancel(); // event je zruseny maze sa
  						} else {
  							// event prebehol
  						}
  					});
  			}.bind(null, id));

  		}

  		response.status = 1;
  		response.new_event_id = results.insertId
  		res(response);
  	});
  });

  // ODSTRANENIE SENSOR Z IZBY

  socket.on('unassign_sensor', function (data, res) {
  	console.log("data id: "+data.id)
  	connection.query('UPDATE `sensors` SET  `room` = 0  WHERE `id` = "'+data.id+'";', function (error, results, fields) {
  		console.log(results);
  		var response = {};
  		response.status = 1;
  		res(response);
  	});
  });

  // ODSTRANENIE OUTPUT Z IZBY

  socket.on('unassign_output', function (data, res) {
  	console.log("data id: "+data.id)
  	connection.query('UPDATE `outputs` SET  `room` = 0 WHERE `id` = "'+data.id+'";', function (error, results, fields) {
  		console.log(results);
  		var response = {};
  		response.status = 1;
  		res(response);
  	});
  });


  // PRIKAZ NA ZMENU OUTPUT

  socket.on('change_output', function (data, res) {  
  	changeValue(data, data.value, function(err, response) {
  		res(response);
  	});
  });

  // AKTIVACIA/DEAKTIVACUA EVENTU

  socket.on('change_event_activity', function (data, res) {  
  	connection.query('UPDATE `events` SET `active` = "'+data.value+'" WHERE `id` = "'+data.id+'";', function (error, results, fields) {
  		var response = {}
  		response.status = 1;
  		res(response);
  	});
  });

  // VYPIS TEPLOT

  socket.on('get_temp_graph', function (data, res) {  
  	connection.query('SELECT * FROM `sensors_record` WHERE `sensor` = ' + data.id +' ORDER BY `id` DESC LIMIT 24 ', function (error, results, fields) {
  		var response = {};
  		response.results = [];
  		
  		for (var i = 0; i <= 24; i++) {

  			if(typeof results[24-i] == "undefined") {
  				response.results.push(15);
  			} else {
  				response.results.push(results[24-i].value);
  			}
  		}

  		response.status = 1;
  		res(response);
  	});
  });


  // Zapnutie a vypnutie kamery
  socket.on('video_on', function (data, res) {
  	console.log("video_on");
  	if(global.video_on == 0) {
  		console.log("video start");
  		child=spawn('raspistill', ['-l', 'testy/image.jpg', '-o', 'Videos/%04d.jpg', '-w', '375', '-h', '281', '-q', '10', '-tl', '500', '-t', '3600000']);
  		global.video_pid = child.pid;
  	}
  	global.video_on++;
  });
  socket.on('video_off', function (data, res) {
  	global.video_on--;
  	if(global.video_on == 0) {
  		console.log("video start");
  		spawn('pkill', ['raspistill']);
  	}
  });

});

// inicializacia radia, DB
rf24.begin(settings.id, settings.tx, settings.rx);
connection.connect();


loop();

video();


function video() {
	if(global.video_on > 0) {
		fs.readFile('testy/image.jpg', function(err, buf){
			io.emit('image', buf.toString('base64'));
		});
	}
	setTimeout(video, 500);    
}



// FUNKCIA PRIJIMANIA SPRAV
function loop() {
	if(rf24.available()) {
		data = rf24.recieve_data();
		if(data.type == "new_device") {
			message = data.message.split(" ");
			console.log(data.message);
			connection.query('SELECT `id` FROM `devices` WHERE  `hash` = "'+message[1]+'"', function (error, results, fields) {
				if(results.length == 0) {
					connection.query('INSERT INTO `devices` (`id`, `code`, `hash`, `type`, `active`) VALUES (NULL, "", "'+message[1]+'", "'+message[0]+'", 0);', function (error, results, fields) {
						if (error) throw error;
					});
				}
				if (error) throw error;
			});
		} else if(data.type == "message") {
			(function(data) {
				setTimeout(function() {
					async.waterfall([
						function(callback) {
							connection.query('SELECT `id` FROM `devices` WHERE  `code` = ' + data.module, function (error, results, fields) {
								var id = results[0].id;
								callback(null, id);
							});
						}, function(id, callback) {
							connection.query('SELECT * FROM `sensors` WHERE `type` = "push" AND `device` = ' + id, function (error, sensors, fields) {
								callback(null, sensors);
								if (error) throw error;
							});
						}], function(err, sensors) {
							console.log(sensors);

							var i_s = 0;
							(function for_sensors() {
								if(i_s < sensors.length) {

									var value = data.message.charAt(sensors[i_s].byte);
									var int_value = parseInt(value);

									connection.query('SELECT * FROM `events` WHERE `sensor` = ' + sensors[i_s].id + ' AND `type` = "sensor" AND `active` = 1 ', function (error, events, fields) {

										if(typeof events != "undefined" && events.length > 0) {

										var time = new Date();
										var i_e = 0;
										var curr = [time.getHours, time.getMinutes];
										console.log(events);

										var timeout = 0;

										if(events[i_e].timeout != 0) {
											timeout = (events[i_e].timeout * 1000 * 60);
										} else {
											timeout = 0;
										}

										(function for_events() {
											if(i_e < events.length) {

												var days = events[i_e].days.split(",");
												var start = events[i_e].start.split(":");
												var stop = events[i_e].stop.split(":");
												var pass = false;

                        // casova podmienka
                        if(typeof days == "undefined" || days.indexOf(time.getDay()) || days.length == 0) {
                        	if(events[i_e].start == "00:00" && events[i_e].stop == "00:00") {
                        		pass = true;
                        	} else if(start[0] < curr[0] &&  start[1] < curr[1] && stop[0] > curr[0] && stop[0] > curr[0]) {
                        		pass = true;
                        	}
                        }
                        if(pass && events[i_e].event_on == int_value) {
                        	connection.query('SELECT * FROM `outputs` WHERE `id` = ' + events[i_e].output, function (error, results, fields) {
                        		if(results[0].value != events[i_e].value) {
                        			var output = Object.assign({},results[0]);
                        			var old_value = results[0].value;
                        			changeValue(output, events[i_e].value, function(err, result) {
                        				if(result.status == 1) {
                        					if(timeout != 0) {
                        						setTimeout(function() {
                        							changeValue(output, old_value, function(err, result) {});
                        						}, timeout);
                        					}
                        				}
                        			});
                        		}
                        		i_e++;
                        		for_events();
                        	});

                        } else {
                        	i_e++;
                        	for_events();
                        }

                    }
                }());

										i_s++;
										for_sensors();

									}
									});

								}
							}());
						});
				}, 500);
			})(data);
		}
		console.log("dt");
	}
	setTimeout(loop, 10);    
}




// CASOVE EVENTY
connection.query('SELECT id, start, days FROM `events` WHERE  `type` = "time"', function (error, results, fields) {
	for(var i in results) {
		var time = results[i].start.split(":");
		var id = results[i].id;
		var jobs = [];

		jobs[id] = schedule.scheduleJob(time[1] + ' ' + time[0] + ' * * ' + results[i].days, function() {
			async.waterfall([
				function(callback) {
					connection.query('SELECT `output`, `value`, `active` FROM `events` WHERE  `id` = ' + id, function (error, results, fields) {
						var info = {};
						if(results.length == 1) {
							if(results[0].active == 1) {
								info.status = 1;
								info.output = results[0].output;
								info.value = results[0].value;
								callback(null, info);
							} else {
								callback('noactive', info);
							}
						} else {
							callback('zero', info);
						}

					});

				}, function(info, callback) {
					if(info.status == 1) {
						connection.query('SELECT * FROM `outputs` WHERE `id` = ' + info.output , function (error, results, fields) {
							var output = Object.assign({},results[0]);
							var value = info.value;
							callback(null, output, value);
						});
					} else {

					}
				}, function(output, value, callback) {
					changeValue(output, value, function(err, result) {
						callback(null, result);
					});

				}], function(err, result) {
					if(err == 'noactive') {
  						// event je neaktivny
  					} else if(err == 'zero') {
  						job.cancel(); // event je zruseny maze sa
  					} else {
  						// event prebehol
  					}
  				});
		}.bind(null, id));
	};
	if (error) throw error;
});


var get_sensors = schedule.scheduleJob('*/5 * * * *', function(){
	time = Math.floor(Date.now() / 1000);
	connection.query('SELECT *, (SELECT `devices`.`code` FROM `devices` WHERE `devices`.`id`=`sensors`.`device` LIMIT 1) AS code FROM `sensors` WHERE  `type` = "request"', function (error, results, fields) {
		for(var i in results) {
			var status = 0;

			var sent = rf24.send_data(results[i].code, "", 0x00, 15);
			if(!sent.status) {
				wait(100);
				sent = rf24.send_data(results[i].code, "", 0x00, 15);
			}
			console.log(sent);

			var value="";
			if(sent.status) {
				for(var j=results[i].byte; j < results[i].byte+results[i].length; j++) {
					value += sent.message.charAt(j);
				}
				status = 1;
			} else {
				status = 0;
			}
			var int_value = parseInt(value);
			if(isNaN(int_value)) {
				int_value = 0;
			}

			connection.query('INSERT INTO `sensors_short_record` (`id`, `sensor`, `value`, `time`, `status`) VALUES (NULL, "'+results[i].id+'", '+int_value+', '+time+', ' + status + ');', function (error, results, fields) {
				if (error) throw error;
			});

		}
		if (error) throw error;
	});
});

var average = schedule.scheduleJob('02 * * * *', function(){
	var time = Math.floor(Date.now() / 1000);
	connection.query('SELECT * FROM `sensors` WHERE  `type` = "request"', function (error, results, fields) {
		for(var i in results) {
			var avg = 0;
			var status = 0;
			var id = results[i].id;
			console.log(time-3600);
			connection.query('SELECT * FROM `sensors_short_record` WHERE  `sensor` = ' + id + ' AND `time` > ' + (time-3600) + ' AND `status` = 1', function (error, results, fields) {
				console.log(results);
				if(typeof results != "undefined") {
					for(var i in results) {
						avg += results[i].value
					}
					console.log(results.length);
					if(results.length > 0) {
						avg = avg/results.length;
						status = 1;
						console.log(avg);
					} else {
						avg = 0;
						status = 0;
					}
					var d = new Date();
					var h = d.getHours() -1;
					if(h < 0) h = 23;
					console.log((new Date()).toISOString().substring(0, 10));
					connection.query('INSERT INTO `sensors_record` (`id`, `sensor`, `value`, `day`, `hour`, `status`) VALUES (NULL, "'+ results[i].sensor +'", '+avg+', "'+ (new Date()).toISOString().substring(0, 10) +'", ' + h + ' , ' + status + ');', function (error, results, fields) {
						if (error) throw error;
					});

				}

				connection.query('DELETE FROM `sensors_short_record` WHERE  `sensor` = ' + id + ' AND `time` < ' + (time-180) , function (error, results, fields) {});

			});

		}
		if (error) throw error;
	});
});




// ODOSLANIE PRIKAZU NA ZMENU

function changeValue(output, value, callback) {

	connection.query('SELECT `code` FROM `devices` WHERE `id` = ' + output.device , function (error, results, fields) {
		var response = {};
		var message = "";
		for(var i = 0; i < output.byte; i++) {
			message +=" ";
		}

		message += value;
		var send = rf24.send_data(results[0].code, message, 0x00, 15);
		if(!send.status) {
			wait(100);
			send = rf24.send_data(results[0].code, message, 0x00, 15);
		}
		console.log(send.status);
		console.log(send.time);

		if(output.type == "termostat") {

		}

		if(send.status) {
			connection.query('UPDATE `outputs` SET `value` = "'+value+'" WHERE `id` = "'+output.id+'";', function (error, results, fields) {});
			if(output.type == "termostat") {
				connection.query('UPDATE `termostats` SET `temp` = "'+output.temp+'" WHERE `output` = "'+output.id+'";', function (error, results, fields) {});
			}
			response.status = 1;
			io.sockets.emit("output_update", {id: output.id, value: value, temp: output.temp});
		} else {
			response.status = 0;
		}
		if (error) console.log("chyba");
		callback(null, response);
	});

}

// GENEROVANIE UNIKATNENO ID PRE MODUL

function new_module_id(callback) {
	var id = Math.floor((Math.random() * 255) + 1);
	console.log("generujem "+id);
	connection.query('SELECT `id` FROM `devices` WHERE `id` = ' + id , function (error, results, fields) {
		if (results.length > 0) {
			new_module_id(function(id) {
				callback(null, id);
			});
		} else {
			callback(null, id);
		}
	});

}


// delay
function wait(ms) {
    var start = Date.now(),
        now = start;
    while (now - start < ms) {
      now = Date.now();
    }
}

process.on('SIGINT', exitHandler);

function exitHandler() {
	process.exit();

	rf24.close();
}