//Global Params
var htmlDateClient = document.getElementById("DateClient");
var htmlDateServer = document.getElementById("DateServer");
var htmlDateSynch = document.getElementById("DateSynch");

var htmlErrMSG = document.getElementById("Error_Message");

var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");

var diagram = new Diagram(0, 0, canvas.width, canvas.height);
diagram.BuildDefault();
diagram.Cycle(true);
var update_button = document.getElementById("Update_Button");
//Global Params

//Show Date Now \/ \/ \/
function FNL(a, b) { for (var d = "" + a; d.length < b;)d = "0" + d; return d }
function DateToString(date) { return date.getFullYear() + "." + FNL(date.getMonth() + 1, 2) + "." + FNL(date.getDate(), 2) + "  " + FNL(date.getHours(), 2) + ":" + FNL(date.getMinutes(), 2) + ":" + FNL(date.getSeconds(), 2); }

var dateClient = null;
var dateServer = null;
var dateSynch = null;
function PrintDateNow() {
  var dn = new Date();
  if (dateServer !== null && dateClient !== null)
    dateServer.setMilliseconds(dateServer.getMilliseconds() + (dn - dateClient));

  dateClient = dn;
  htmlDateClient.innerHTML = DateToString(dateClient);
  if (dateServer != null)
    htmlDateServer.innerHTML = DateToString(dateServer);
  if (dateSynch !== null)
    htmlDateSynch.innerHTML = DateToString(dateSynch);

  setTimeout(PrintDateNow, 1000);
}
function updateDateServer(date) {
  if (typeof date.getMonth === 'function') {
    dateClient = null;
    dateServer = date;
  } else
    dateServer = null;
}
function updateDateSynch(date) {
  if (typeof date.getMonth === 'function') {
    dateSynch = date;
  } else
    dateSynch = null;
}
PrintDateNow();
//Show Date Now /\ /\ /\

//Resize Canvas \/ \/ \/
function Resize() {
  if (window.innerWidth > window.innerHeight) {
    canvas.height =
      window.innerHeight - 20
      - document.getElementById("First_Head").offsetHeight
      - document.getElementById("Second_Head").offsetHeight
      - document.getElementById("Third_Head").offsetHeight;
    canvas.width = document.getElementById("Canvas_Body").offsetWidth;
    diagram.Rotate(false);
    diagram.RectParam(0.5, 0.5, canvas.width - 1, canvas.height - 1);
  }
  else {
    canvas.height = diagram.ProcCount() * 25;
    canvas.width = document.getElementById("Canvas_Body").offsetWidth;
    diagram.Rotate(true);
    diagram.RectParam(0.5, 0.5, canvas.width - 1, canvas.height - 1);
  }
  ctx = canvas.getContext("2d");
  diagram.Print(ctx);
}
window.addEventListener("load", Resize, false);
window.addEventListener("resize", Resize, false);
//Resize Canvas /\ /\ /\

//Autoprint diagram \/ \/ \/
function PrintCycle() {
  diagram.Print(ctx);
  setTimeout(PrintCycle, 1000);
}
PrintCycle();
//Autoprint diagram /\ /\ /\

//Update Status \/ \/ \/
function UpdateStatus() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'api/currcycles', true);
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState != 4) return;
    if (xhr.status != 200) {
      htmlErrMSG.innerHTML = "Не удается установить соединение";
      $("#Error_Border").show();
      $("#Update_Button").show();
      return;
    }
    else
      $("#Error_Border").hide();
    var data = JSON.parse(xhr.responseText);
    if (data.currTime === undefined) {
      htmlErrMSG.innerHTML = "Ошибка в полученных данных: отсутствует время сервера";
      $("#Error_Border").show();
      $("#Update_Button").show();
      return;
    }
    updateDateSynch(new Date());
    updateDateServer(new Date(data.currTime));

    if (data.data === undefined || !Array.isArray(data.data)) {
      htmlErrMSG.innerHTML = "Ошибка в полученных данных: отстутствует массив днных";
      $("#Error_Border").show();
      $("#Update_Button").show();
      return;
    }

    var p = data.data;
    for (var i = 0; i < p.length; i++) {
      var idx = p[i].vdp - 1;
      var s = -1;
      var b = -1;
      switch (p[i].cycle) {
        case 0: s = 0; b = -1; break;
        case 1: s = 0; b = 1; break;
        case 2: s = 1; b = 0; break;
        case 5: s = 2; b = 0; break;
        case 6: s = 3; b = 0; break;
        case 7: s = 4; b = 0; break;
        case 8: s = 5; b = 3; break;
        case 9: s = 6; b = 3; break;
        case 10: s = 7; b = 3; break;
        case 11: s = 8; b = 3; break;
        case 12: s = 9; b = 3; break;
        case 14: s = 1; b = 1; break;
        case 15: s = 2; b = 1; break;
        case 16: s = 3; b = 1; break;
        default: s = -1; b = -1;
      }
      diagram.ChangeStatProc(idx, s, 0);
      diagram.ChangeStatBlink(idx, b);
      diagram.StartDate(idx, new Date(p[i].factStart));
      diagram.EndDate(idx, new Date(p[i].thinkEnd));
    }
    diagram.Cycle(true);

    /*
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (var i = 1; i <= diagramStove.ProcessCount(); i++) {
      diagramStove.ChangeStatBlink(i, Pech[i].Bstatus);
      diagramStove.ChangeStatProc(i, Pech[i].Pstatus);
      diagramStove.ChangeStartDate(i, ConvDate(Pech[i].Start));
      diagramStove.ChangeEndDate(i, ConvDate(Pech[i].EndTeor));
    }
    var b = ConvDate(Pech[0].DateNow);
    dateUpdateHTML.innerHTML =
      b.getFullYear() + "." +
      FNL(b.getMonth() + 1, 2) + "." +
      FNL(b.getDate(), 2) + "  " +
      FNL(b.getHours(), 2) + ":" +
      FNL(b.getMinutes(), 2) + ":" +
      FNL(b.getSeconds(), 2);
    if (Math.abs(b - new Date()) > 60000) {
      document.getElementById("Error_Message").innerHTML = "Разница между системным и серверным временем " + Math.floor(Math.abs(b - new Date()) / 1000) + " сек";
      $("#Error_Border").show();
      $("#Update_Button").hide();
    }
    else
      $("#Error_Border").hide();
      */
    diagram.Print(ctx);
    setTimeout(UpdateStatus, 60 * 1000);
  }
}
UpdateStatus();

function ConvDate(a) {
  a = a.split(".")[0].split("T");
  var d = a[0].split("-");
  var h = a[1].split(":");
  var date = new Date(d[0], parseInt(d[1]) - 1, d[2], h[0], h[1], h[2]);
  return date;
}

update_button.onclick = function () {
  UpdateStatus();
}
//Update Status /\ /\ /\


//End Update Status




/*
//End Show Date Now




*/