var appctl, appinfo, appctltimer, appinfotimer;
var app_indicator = document.getElementById("app-indicator");
var app_start = document.getElementById("app-start");
var app_stop = document.getElementById("app-stop");
var app_view = document.getElementById("app-view");
var app_req = document.getElementById("app-req");
var app_rel = document.getElementById("app-rel");
var app_info = document.getElementById("app-info-label");

var url = sessionStorage.getItem("api");
var appid = sessionStorage.getItem("appid");
var user = sessionStorage.getItem("user");

if(user) {
    try {
        user = JSON.parse(user);
    } catch(e) {}
}

function appReq(url, req, appid, get, callback) {
  var method, xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
	if(this.readyState == 4){
      if(this.status == 200) {
		if(get == 1){  
	      callback(JSON.parse(this.response), this.status);
		}else{
		  callback(this.response, this.status);
		}
      }else if(this.status == 0){
		App(0);
	  }else{
	    callback(this.response, this.status);
	  }
	}
  };
  if(get == 1){
	method = "GET";
  }else{
    method = "POST";
  }
  xhttp.open(method, url+req+appid, true);
  xhttp.withCredentials = true;
  xhttp.send();
}

function AppInfo(callback){
  appReq(url, "/app/info/", appid, 1, function(arg, status){  
	if(status == 200){ 
	  appinfo = arg;
	  sessionStorage.setItem("appinfo", JSON.stringify(arg));
	}
	callback();
  });
}

function AppCtlInfo(callback){
  appReq(url, "/app/control/info/", appid, 1, function(arg, status){  
	if(status == 200){ 
	  appctl = arg; 
	  sessionStorage.setItem("appctl", JSON.stringify(arg));
	}else if(status == 404){
	  clearInterval(appctltimer);
	  clearInterval(appinfotimer);
	  AppInfoTimerF();		
	}else if(status == 403){
	  appctl = JSON.parse('{"master":"0","reserved":"0","view":"0","queue":"0","end":"0","limit":"0","requested":"0","position":"0","used":"0"}');
	  sessionStorage.setItem("appctl", JSON.stringify(appctl));
	  App();
	}
	callback();
  });
}

function AppCtlInfoTimerF(){
  appctltimer = setInterval(function() {
	AppCtlInfo(function(){ App(); }); 
  }, 5000);	
}

function AppInfoTimerF(){
  appinfotimer = setInterval(function() {
	AppInfo(function(){ 
	  if(appinfo.state == "1"){
		clearInterval(appinfotimer);	
		AppCtlInfo(function(){ App();
		  AppCtlInfoTimerF();
		});
	  }else{ App(); }
	}); 
  }, 5000);	
}

//window.onload = function(){
  AppInfo(function(){  		    
	if(appinfo.state == "1"){
	  AppCtlInfo(function(){ App(); 
		AppCtlInfoTimerF();
	  }); 
	}else{
	  App();
	  AppInfoTimerF();
	}
  });
//};

app_view.children[1].innerHTML = "Zobrazenie";
app_req.children[1].innerHTML = "Požiadať o kontrolu";
app_rel.children[1].innerHTML = "Odovzdať kontrolu";
app_indicator.classList.remove("on");
app_start.disabled = true;
app_stop.disabled = true;
app_view.firstChild.classList.add("off");
app_view.disabled = true;
app_req.disabled = true;
app_req.firstChild.classList.remove("check");
app_req.style.display = "flex";
app_rel.style.display = "none";
  
function App(status){

if(status == 0){
  app_info.innerHTML = "&#x26A0; Chyba spojenia";
  app_indicator.classList.remove("on");
  app_start.disabled = true;
  app_stop.disabled = true;
  app_view.firstChild.classList.add("off");
  app_view.disabled = true;
  app_req.disabled = true;
  app_req.children[1].innerHTML = "Požiadať o kontrolu";
  app_req.firstChild.classList.remove("check");
  app_req.style.display = "flex";
  app_rel.style.display = "none";
  
  appctl = JSON.parse('{"master":"0","reserved":"0","view":"0","queue":"0","end":"0","limit":"0","requested":"0","position":"0","used":"0"}');
  sessionStorage.setItem("appctl", JSON.stringify(appctl));
  
  clearInterval(appinfotimer);
  clearInterval(appctltimer);	
}else{

if(appinfo.state == "1"){ 
  app_indicator.classList.add("on");	
  app_start.disabled = true;
  app_view.disabled = true;
  app_req.disabled = true;
	
  if(appctl.master == "1"){
	app_info.innerHTML = "V kontrole";	
	
	app_req.style.display = "none";
	app_rel.style.display = "flex";
	app_stop.disabled = false;
	app_view.disabled = false;
	app_rel.disabled = false;
	
	if(appctl.queue == "1"){
	  app_info.innerHTML = "Ostáva"+'&nbsp;<span id="app-ctd-label"></span>';
	  
	  var app_info_ctd = document.getElementById("app-ctd-label");
	  var ctdDate = new Date(appctl.end*1000);
	  var x = setInterval(function() {
  	    var now = new Date().getTime();
  	    var dist = ctdDate - now;

  		var hours = Math.floor((dist % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  		var minutes = Math.floor((dist % (1000 * 60 * 60)) / (1000 * 60));
  		var seconds = Math.floor((dist % (1000 * 60)) / 1000);
  
  		var h = hours + "h ";
  		var m = minutes + "m ";
  		var s = seconds + "s ";
   
  		if(h > 0){  
   		  app_info_ctd.innerHTML = h+m+s;
  		}else{  
   		  app_info_ctd.innerHTML = m+s;
  		}
	
  		if (dist < 0) {
    	  clearInterval(x);
    	  app_info_ctd.innerHTML = "0m 0s";
  		}
	  }, 1000);
	} 

	if(appctl.reserved == "1"){
	  app_rel.disabled = true;
	  app_view.disabled = true;
	  var date = new Date(appctl.end*1000);
	  var h = "0" + date.getHours();
	  var m = "0" + date.getMinutes();
	  var dt = date.getDate()+"."+(date.getMonth()+1)+" "+h.substr(-2)+":"+m.substr(-2);
	  app_info.innerHTML = "Rezervované do "+dt;
    }else{
	
	}
  }else{
	app_info.innerHTML = "Spustené";
	
	if(appctl.used == "1"){
	  app_info.innerHTML = "Obsadené";
	}
	 
	app_req.style.display = "flex";
	app_rel.style.display = "none";
	app_stop.disabled = true;
	app_view.disabled = true;
	
	if(appctl.requested == "1"){
	  app_info.innerHTML = appctl.position+". v poradí";
	  
	  app_req.children[1].innerHTML = "Požiadané";
	  app_req.firstChild.classList.add("check");
	  app_req.disabled = true;
	}else{
	  app_req.children[1].innerHTML = "Požiadať o kontrolu";
	  app_req.firstChild.classList.remove("check");
	  app_req.disabled = false;
	}
	
	if(appctl.reserved == "1"){
	  app_info.innerHTML = "Rezervované";
	  app_req.disabled = true;
	}

  }

  if(appctl.view == "1"){
    if(appctl.master == "0" && appctl.reserved == "1"){
	  app_view.firstChild.classList.add("off");
	}else{
	  app_view.firstChild.classList.remove("off");
	}
  }else{
	app_view.firstChild.classList.add("off");	
  }
  
  app_stop.onclick = function(){
	appReq(url, "/app/stop/", appid, 0, function(arg, status){
	  if(status == 200){ 
	  	AppInfo(function(){ 
		  App(); 
		  clearInterval(appctltimer);
		  clearInterval(appinfotimer);
		  AppInfoTimerF(); 
		});
	  }else if(status == 500){
	    app_info.innerHTML = "&#x26A0; Chyba pri zastavovaní";
	  }else if(status == 403){
		var err = JSON.parse(arg);
		if(err.code == "122"){
		  OpenModalHTML("Oznam", "250px", "", '<p style="text-align:center;">Zastavnie nepovolené, existujú požiadavky o kontrolu.</p>');  
		}
	  }
	});  
  }
  app_view.onclick = function(){
	appReq(url, "/app/control/view/", appid, 0, function(arg, status){
	  AppCtlInfo(function(){ App(); });
	});
  }
  app_req.onclick = function(){
	appReq(url, "/app/control/request/", appid, 0, function(arg, status){
	  AppCtlInfo(function(){ App(); });
	});
  }
	app_rel.onclick = function(){
	appReq(url, "/app/control/release/", appid, 0, function(arg, status){
	  if(status == 200){ AppCtlInfo(function(){ App(); }); }
	});
  }
}else{
  app_info.innerHTML = "Zastavené";
  
  clearInterval(appinfotimer);
  clearInterval(appctltimer);  
  
  app_indicator.classList.remove("on");
  app_start.disabled = false;
  app_stop.disabled = true;
  app_view.firstChild.classList.add("off");
  app_view.disabled = true;
  app_req.disabled = true;
  app_req.children[1].innerHTML = "Požiadať o kontrolu";
  app_req.firstChild.classList.remove("check");
  app_req.style.display = "flex";
  app_rel.style.display = "none";

  app_start.onclick = function(){
	appReq(url, "/app/start/", appid, 0, function(arg, status){
	  if(status == 200){ 
	    AppInfo(function(){  		    
	      AppCtlInfo(function(){ App();
	        clearInterval(appctltimer);
			clearInterval(appinfotimer);
	        AppCtlInfoTimerF();
	      }); 
        });	
	  }else if(status == 500){
	    app_info.innerHTML = "&#x26A0; Chyba pri spúšťaní";
	  }else if(status == 403){
		var err = JSON.parse(arg);
		if(err.code == "114"){
		  OpenModalHTML("Oznam", "250px", "", '<p style="text-align:center;">Aplikácia je rezervovaná.</p>');  
		}
	  }  
	}); 
  }
}

if(appinfo.guest == "0"){ 
  if(user == "" || user.uid < 0 || !user.uid || user == "not"){
	app_info.innerHTML = "&#x26A0; Prihláste sa";
	
    app_start.disabled = true;
    app_stop.disabled = true;
    app_view.disabled = true;
    app_req.disabled = true;
    app_rel.disabled = true;
  
    clearInterval(appinfotimer);
    clearInterval(appctltimer);	
  }
}

if(appinfo.ctl == "0"){ 
  app_start.disabled = true;
  app_stop.disabled = true;
}

}

}