/*
////////////////////////////////////////////

nodescore server
nodescore.kiben.net
nodescore@kiben.net

////////////////////////////////////////////
*/

var sio = require('socket.io')
, http = require('http')
, ch = require('./chronometer')
, osc = require('node-osc')
, fs = require('fs');
//, static = require('node-static');

// start oscgroups client in a screen
//var sys = require('sys')
//var exec = require('child_process').exec;
//exec("./oscgroupsclient_start.sh");

var oscclient = new osc.Client('localhost', 22243);
    function oscChron(unit,voice,counter){	
	oscclient.send('/nodescore/voice_'+voice,unit,counter);
    }

var argu = process.argv.splice(2);
var port = argu[0]
var www = argu[1]

console.log(www, port)

var requirejs = require('requirejs');

requirejs.config({
    //Pass the top-level main.js/index.js require
    //function to requirejs so that node modules
    //are loaded relative to the top-level JS file.
    nodeRequire: require,
    findNestedDependencies: true
});

// run webserver serving static html
////////////////////////////////////////////
var express = require("express"),
    app = express(),
    //bodyParser = require('body-parser')
    errorHandler = require('errorhandler'),
    methodOverride = require('method-override'),
    port = parseInt(process.env.PORT, 10) || port;

app.get("/", function (req, res) {
  res.redirect("/index.html");
});

app.use(methodOverride());
//app.use(bodyParser());
app.use(express.static(__dirname + '/' + www));
app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));


// Create a Node.js based http server on port 8080
var server = require('http').createServer(app).listen(port);
////////////////////////////////////////////

var pinging=0
console.log("ping set to 0")

//requirejs(['socketsstuff'],function(socketsstuff) {});
////////////////////////////////////////////
// connect to websockets 
////////////////////////////////////////////

io = sio.listen(server)
, nicknames = {};

//var sequencer = require('./sequencer')

//io.set('log level', 4); // reduce logging
io.sockets.on('connection', function (socket) {

    socket.on('nickname', function (nick, fn) {
	if (nicknames[nick]) {
	    fn(true);
	} else {
	    fn(false);
	    nicknames[nick] = socket.nickname = nick;
	    socket.broadcast.emit('announcement', nick + ' connected');
	    io.sockets.emit('nicknames', nicknames);
	}
    });  
    
    /// chat user messages to screens and to log file
    // date format for filename
    var da = new Date(); var dtstring = da.getFullYear()+ '-' + da.getMonth()+ '-' + da.getDate();
    ////////////////////////
    /// log messages to file
    socket.on('user message', function (msg) {
	fs.open('logs/chatlog-'+dtstring+'.txt', 'a', 666, function( e, id ) {	
	    //time format for message stamp
	    var dt = new Date();var timestring = dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds();
	    socket.broadcast.emit('user message', socket.nickname, msg);	    
	    var fs = require('fs'), str = msg;
	    fs.write( id, timestring+" " + socket.nickname + ": "+ msg+"\n", null, 'utf8', function(){});
	});	
    });

    ////////////////////////////////////////////
    // chronometer + sequencer controls (all this should be modularised)
    ////////////////////////////////////////////

    sstate=0;
    socket.on('stopWatch', function (state) { stopWatch(state);});
    socket.on('stopChr',  function () { 
	//sstate=0;  
	stopChr(); 

    });    
   
    socket.on('resetChr', function () { 
	//reset currently just restarts current unit
	//todo: make a total reset that sets unit and transect to 0
	resetChr();  
    });
   
    socket.on('startSeq', function () { 
	//if( sstate==0 ){ 
	    startChr();  
	  //  sstate=1;
	//}
    });  
    
    var chronstate=0;

    // send the date/time every second

    xdatetime =  setInterval(function () {
	d =  ch.xdateTime()
	socket.broadcast.emit('dateTime', d)
	socket.emit('dateTime', d)	
    }, 1000)
              
    //////////////////////////////
    //    /* this should be moved to its own file chronometer.js
    
    function chronCtrl (state,interval){
	if (state==1){ console.log("chronControl....onestate")
		       var date = new Date(); var starttime = new Date().getTime() / 1000;
		       xstopwatch =  setInterval(function () {
			   var nowtime = new Date().getTime() / 1000;
			   now = nowtime-starttime
			   hours = parseInt( now / 3600 ) % 24;
			   minutes = parseInt( now / 60 ) % 60;
			   seconds = parseInt(now  % 60);
			   milliseconds = Math.floor((now-seconds)*10)%60;
			   time = 
			       (hours < 10 ? "0" + hours : hours) + ":" + 
			       (minutes < 10 ? "0" + minutes : minutes) + ":" + 
			       (seconds  < 10 ? "0" + seconds : seconds) + "."+ 
			       milliseconds;
			   socket.broadcast.emit('chronFromServer', time)
			   socket.emit('chronFromServer', time)
			   oscclient.send('/nodescore/time',time);		   
		       }, 100)
	
	     }
	
	if (state==0) { console.log("chronControl....zerostate") ; clearInterval(xstopwatch); }	
   
    }

    // if not already started start the chronometer and sequencer    
    function startChr(socket) { 
	chronCtrl(1,100); 
	// these seq[A-D] arrays come from scoreB.js and then become the seq variable
	step(seqA);
	step(seqB); 
	step(seqC); 
	step(seqD); 
    }

    // stop the chronometer   
    function stopChr() { console.log("stop chron"); chronCtrl(0); }  
    
    function pad(number) { return (number < 10 ? '0' : '') + number }
    function resetChr() {//clearInterval();
	zecsec = 0; seconds = 0; mins = 0; hours = 0; 
	var chron = pad(hours) +":"+pad(mins)+ ':'+ pad(seconds)+ ":"+ zecsec
	// send 0.00.00 values to display
	socket.broadcast.emit('chronFromServer', chron)
	socket.emit('chronFromServer', chron)
    }

    ////////////////////////////////////////////
    // magic square sequencer (this should be modularised)
    ////////////////////////////////////////////
    // all the variables this sequencer needs are in scoreB.js
    requirejs(['scoreB'],function(scoreB) {});
    

    socket.on('setSpeed', function (s) {

	speed=s;
	console.log("speed set: " + speed);
    });

    var sequencerState=0;
    var numberoftransects=3;
    var order=8;
    var countdowntick=function(seq){
	var unit=seq.units[seq.transect%numberoftransects][seq.counter];
	var unitlast=seq.units[seq.transect%numberoftransects][seq.counter-1];
	var voice=seq.voice;
	var tempoms = Math.floor(60000/seq.mm);	
	var timemultiplier=1000;
	var outcount=4; var incount=4;
	var dur=srcsqr[Math.floor(unit/order)][unit%order] + 4
	var time = dur;
	var ztime=time; 
	var totaltime=time


	initPage=function(seq){
	    // initiate first page here
	    //var nextunit=seq.units[seq.transect%numberoftransects][(seq.counter+1)%order];
	    //socket.emit("pageIni", voice, unit, time, seq.mm,seq.counter,nextunit );
	    //socket.broadcast.emit("pageIni", voice, unit, time, seq.mm,seq.counter,nextunit );
	   
	    //socket.emit("pageFlip", voice, unit, time, seq.mm,seq.counter,nextunit );
	    //socket.broadcast.emit("pageFlip", voice, unit, time, seq.mm,seq.counter,nextunit );
	}




	function sequenCer() {
	    if (ztime >= 0 ){	
		var counter = ztime
		// flip the page 
		if (counter == 0){	
		    //increment the row position
		    seq.counter = (seq.counter + 1) % (order)	    				
		    //increment the transect
		    if ( seq.counter==0 ){ seq.transect += 1 }
		    // this flips the page at the begining of each new sequence
		    // the similar pageIni function checks if there is and svg loaded
		    // so late joining clients and post page refresh views are up to date
		    
		    var nextunit=seq.units[seq.transect%numberoftransects][(seq.counter+1)%order];
		    console.log("pageflip:" + voice, unit+1, time, seq.mm,seq.counter,nextunit)
		    socket.broadcast.emit("pageFlip", voice, unit+1, time, seq.mm,seq.counter,nextunit);
		    socket.emit("pageFlip", voice, unit+1, time, seq.mm,seq.counter,nextunit);
		    oscclient.send('/nodescore/voice_'+voice +"/unit/" ,unit,Math.floor(Math.random(0,5)));
		    clearInterval(pulse)
		    step(seq);     
		}
		
		if (counter >= 0 ){
		    socket.broadcast.emit('counterText', 
					  voice, unit, counter,seq.counter,unitlast,seq.transect%numberoftransects);
		    oscChron(unit,voice,counter);
		    socket.emit('counterText',
				voice, unit, counter,seq.counter,unitlast,seq.transect%numberoftransects);
		    
		    if (counter <= outcount ) {
			socket.broadcast.emit('countinFromServer', 
					      voice, counter, 
					      "","stop in: ", "red", "transparent",unit);
			socket.emit('countinFromServer', 
				    voice, counter, 
				    "","stop in: ", "red", "transparent",unit);
		    }
		    
		    if (counter > (totaltime)-incount  && counter <= totaltime ) {
			socket.broadcast.emit('countinFromServer',
					      voice, counter-(totaltime-incount), 
					      "","play in: ", "green","transparent",unit);
			socket.emit('countinFromServer',
				    voice,counter-(totaltime-incount), 
				    "","play in: ", "green","transparent",unit);
		    }
		    
		    if (counter == (totaltime)-incount ) {
			socket.broadcast.emit('countinFromServer',
					      voice, "+", 
					      "","playing.. ", "green","transparent",unit);
			socket.emit('countinFromServer',
				    voice, "+",
				    "","playing.. ", "green","transparent",unit);
		    }
		}
		
		// on each beat do:		
		// push out the pulse to metronome	
		
		seq.metrobeat = (seq.metrobeat+1)%seq.beatsinbar ;
     		socket.broadcast.emit('metroPulse', tempoms, voice, seq.metrobeat); 
		socket.emit('metroPulse', tempoms, voice, seq.metrobeat);
		var nextunit=seq.units[seq.transect%numberoftransects][(seq.counter+1)%order];
	    	socket.broadcast.emit("pageIni", voice, unit, time, seq.mm,seq.counter,nextunit );
	    	socket.emit("pageIni", voice, unit, time, seq.mm,seq.counter,nextunit );
		//socket.broadcast.emit("pageFlip", voice, unit, time, seq.mm,seq.counter,nextunit );
	    	//socket.emit("pageFlip", voice, unit, time, seq.mm,seq.counter,nextunit );
	    }

	    // decrement the time 
	    ztime -= 1
	    // this shows undefined counter output - bug related	    
	    //	    console.log(counter)
	}
	
	//trigger a page refresh when the solo voice is changed



	socket.on('changeSoloVoice', function () {
	    var nextunit=seq.units[seq.transect%numberoftransects][(seq.counter+1)%order];
	    socket.broadcast.emit("pageFlip", voice, unit, time, seq.mm,seq.counter,nextunit );
	    socket.emit("pageFlip", voice, unit, time, seq.mm ,seq.counter,nextunit );
	});


	var pulse = setInterval(sequenCer, tempoms);
	socket.on('breakSeq', function () {
	    //this should break the code which will auto-restart under node-supervisor
	    //aka hard reset
	    someAbsentFunction(breakmenow);
	});

	socket.on('stopSeq', function () {
	    sequenCer.clearInterval
	    console.log("sequencer stopping...")	    
	    
	    // grrr why wont this clearInterval work
	    
	    sequencerState = 0
	    clearInterval(pulse)

	    // the below breaks things but maybe this is for the best
	    // without breakage and nodejs supervisor restart then too many instances
	    // mount up and slow thinks down until crash
	    //sequenCer.clearInterval(pulse)
	    

	    stopChr();	    
	});
    };
    
    step = function (seq) {
	clearInterval(countdowntick);
	countdowntick(seq)
	sequencerState=1;
	initPage(seq)
    };
    
    socket.on('resetSeq', function () { 
	// start stop reset in sucession to setup page easy never mind the below
	//var unit=seq.units[seq.transect%numberoftransects][seq.counter];
	resetChr(); 
	//socket.emit("pageIni", 1, unit, 0, 60, 0,1 )
	//socket.emit("pageIni", 2, 1, 0, 60, 0,1 );
	//socket.emit("pageIni", 3, 1, 0, 60, 0,1 );
	//socket.emit("pageIni", 4, 1, 0, 60, 0,1 );
    });

    ////////////////////////////////////////////  
    // some latency calculations
    ///////////////////////////////////////////
    
    /*
      a ping is periodically broadcast to all connected clients each
      connected returns a pong to the server via an "emit" and in turn
      the server returns each unique client a report of the latency
      via another emit - the emit only sends to the source of the
      request, whereas the broadcast.emit..  broadcasts.. ie to all
      connected clients
      
      TODO: smooth range and average out results to remove erratic ping
      times.

      TODO:
      The result then needs to be used to stagger outgoing messages to
      compensate for latency - how much compensation is more connected
      to the time that any audio/video feed needs to encode/decode as
      the latency of the route from node A to node B is inavoidable?!
      so maybe latency is irrelevant in this context - we just need to
      stagger signals according to encoding decoding times.. hmmm
    */


// periodically broadcast a ping
    function serverTime(freq) {
	if (pinging==0){ st = setInterval(function() {
	    var pinging=1;
	    var d = new Date(); var n = d.getTime(); 
	    socket.emit("timeFromServer", n); 
	}, 1000);   } else console.log("already pinging")
    }
    // receive the pong calculate the latency and
    // return the response to the client

    socket.on("clientTimeResponse", function(x) {
	var d = new Date(); var n = d.getTime();
	var latency = (n-x)/2;
	//console.log("SERVERTIME:"+x + " LATENCY:" + latency);
	socket.emit("latencyFromServer", latency);
    });	      
    
    serverTime(1000);
    
    socket.on('disconnect', function(client) {	
	console.log(socket.nickname + " is gone..." )
	clearInterval(st);
	
	if (!socket.nickname) return;
	
	delete nicknames[socket.nickname];
	socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
	socket.broadcast.emit('nicknames', nicknames);
    });

});

exports.socket= io.sockets;
exports.httpServer = server;
