/*
////////////////////////////////////////////
nodescore server
nodescore.kiben.net
nodescore@kiben.net
////////////////////////////////////////////
*/

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

var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"};

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
});

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

// run webserver serving static html
////////////////////////////////////////////
var httpServer = connect()
  .use(connect.logger('dev'))
  .use(connect.static('www'))
  .use(function(req, res){
    res.end('404\n');
  })
 .listen(8890);

////////////////////////////////////////////
// connect to websockets 
////////////////////////////////////////////


io = sio.listen(httpServer)
, 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)
    ////////////////////////////////////////////

    socket.on('stopWatch', function (state) { stopWatch(state);});
    socket.on('stopChr', function () { stopChr();  });    
    socket.on('resetChr', function () { resetChr();});
    socket.on('startSeq', function () { startChr(); });  
    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)
		       }, 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); 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) {});
    
    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
	    socket.emit("pageIni", voice, unit, time, seq.mm,seq.counter,seq.nextunit );
	    socket.emit("pageFlipfromserver", voice, unit, time, seq.mm,seq.counter,seq.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 }
		    socket.broadcast.emit("pageFlipfromserver", voice, unit, time, seq.mm,seq.counter,seq.nextunit);
		    clearInterval(pulse)
		    step(seq);     
		}
		
		if (counter >= 0 ){
		    socket.broadcast.emit('counterText', 
					  voice, unit, counter,seq.counter,unitlast,seq.transect%numberoftransects);
		    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);
	    }
	    
	    // decrement the time 
	    ztime -= 1

// this shows undefined counter output - bug related	    
//	    console.log(counter)
	}
	
	var pulse = setInterval(sequenCer, tempoms);
	
	socket.on('stopSeq', function () {
	    sequenCer.clearInterval
	    console.log("sequencer stopping...")	    
	    // grrr why wont this clearInterval work
	    sequencerState = 0
	    clearInterval(pulse)
	    sequenCer.clearInterval(pulse)
	    stopChr();	    
	});
    };
    
    step = function (seq) {
	clearInterval(countdowntick);
	countdowntick(seq)
	sequencerState=1;
	initPage(seq)
    };
    
    socket.on('resetSeq', function () { resetChr(); });

    ////////////////////////////////////////////  
    // 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 = httpServer;


