//
// Boulder timer
// (c) 2018 Art Trushin, extreme@udm.ru
//

var tim = 0;
var interval = 4;
var interval2 = 0;
var prev_timer_string;
var startDate = new Date();
var timer_handler;
var started = false;
var final_round = false;

var PORT = 8008;
 
var options = {
//    'log level': 0
};
 
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server, options);
server.listen(PORT);
 
app.use('/static', express.static(__dirname + '/static'));
 
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/indexn.html');
});
//подписываемся на событие соединения нового клиента
io.sockets.on('connection', function (client) {
    //подписываемся на событие message от клиента
    client.on('start', function (message) {
        try {
            startTimer(message);
        } catch (e) {
            console.log(e);
            client.disconnect();
        }
    });
    client.on('reset', function (message) {
        try {
            stopTimer(message);
        } catch (e) {
            console.log(e);
            client.disconnect();
        }
    });
});

function pad(num,len)
{
    return(1e15 + num + "").slice(-len);
}

function startTimer(params) {
      if (started){
          stopTimer(params);
      }
      started = true;
      if (params.hours > 0){
          startDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), params.hours, params.mins);
          final_round = false;
      } else {
          startDate = new Date();
          final_round = true;
          console.log("final round");
      }
      interval = params.interval;
      interval2 = params.interval2;
      timer_handler = setInterval(updateTimer, 200);
}

function stopTimer(params) {
      clearInterval(timer_handler);
      interval = params.interval;
      interval2 = params.interval2;
      io.sockets.emit("timer", {timer_val: pad(interval, 1) + ":00", mode: "stop"});
      started = false;
}

function updateTimer() {

    var nowDate = new Date();
    var t;
    if (nowDate < startDate){
        t = startDate - nowDate;
        timer_mode = "stop";
    }else{
        t = nowDate - startDate;
	delta = 0; // если задан interval2, нужна дельта в 1 секунду, чтобы время перехода на табло начиналось с interval2, а не на секунду меньше
	if (interval2 > 0) {
	    delta = 1000;
	}
        if (final_round && t > (interval * 60000)) {
            t = 0;
            stopTimer({interval: interval, interval2: interval2});
        } else {
            t = t % (interval * 60000 + (interval2*1 + 1) * 1000 + delta);
            t = interval * 60000 + (interval2*1 + 2) * 1000 - t;
        }
        if(t > (interval2 * 1000 + 1000)){ // или без +1000, чтобы 00 было зеленым
            timer_mode = "timer";
            t = t - interval2 * 1000 - 1000;
        } else {
            timer_mode = "timer2";
            t = t;
        }
    }
    var m = (t - t % 60000) / 60000;
    var s = t % 60000;
    s = (s - s % 1000) / 1000;
    if (timer_mode == "timer" && m == 0 && s == 5){
        io.sockets.emit("playGong");
    }else if ( (interval2 > 0 || final_round) && m == interval && s == 0){
        io.sockets.emit("playStart");
    }else if (m == 1 && s == 0){
        io.sockets.emit("playMin");
    }
    var timer_string = pad(m, 1) + ":" + pad(s, 2);
    if (timer_string != prev_timer_string){
        io.sockets.emit("timer", {timer_val: timer_string, mode: timer_mode});
        prev_timer_string = timer_string;
    }
    console.log(timer_string);
};