var lines;
var subscription;
var ws;
var acts = {};
var transitions = [];
var lastpos;

var sub = 'topic'  + '=' + 'activity' + '&' +// {{{
          'events' + '=' + 'calling' + '&' +
          'topic'  + '=' + 'condition' + '&' +
          'events' + '=' + 'eval' + '&' +
          'topic'  + '=' + 'dataelements' + '&' +
          'events' + '=' + 'change' + '&' +
          'topic'  + '=' + 'position' + '&' +
          'events' + '=' + 'change';// }}}

function transdraw() {
  var buff = [];
  while (transitions.length > 0) {
    var trans = transitions.shift();
    if (acts[trans.unmark] && acts[trans.at]) {
      $(lines).each(function(k,val){
        if (val['From']  == acts[trans.unmark] && val['To']  == acts[trans.at]) {
          changelines('green','red');
          drawline(val['From'],val['To'],val['Between'],'green');
        }
      });
    } else {
      buff.push(trans);
    }
  }
  transitions = buff;
}

function transdraw2(station) {
  if (lastpos) {
    $(lines).each(function(k,val){
      if (val['From']  == lastpos && val['To']  == station) {
        changelines('green','red');
        drawline(val['From'],val['To'],val['Between'],'green');
        //console.log(lastpos);
      }
    });
  }
  lastpos = station;
}

function websocket() { //{{{
  var url = $('body').attr('current-instance');
  var Socket = "MozWebSocket" in window ? MozWebSocket : WebSocket;
  if (ws) ws.close();
  ws = new Socket(url.replace(/http/,'ws') + "/notifications/subscriptions/" + subscription + "/ws/");
  ws.onopen = function() {
    console.log("monitoring", "opened", "");
  };
  ws.onmessage = function(e) {
    data = $.parseXML(e.data);
    if ($('event > topic',data).length > 0) {
      switch($('event > topic',data).text()) {
        case 'condition':
          var data = JSON.parse($('event > notification',data).text());
          if (data.condition == "true") {
            $('#detailcolumn .stations').append($('<div class="station-condition">' + data.code + '</div>'));
          }
        case  'dataelements':
        	var data = JSON.parse($('event > notification',data).text());
        	var schrott = data.values.schrott;
          console.log(schrott);
          console.log(schrott["tatsächlicher Status"]);
          console.log(schrott["schrott"]);
        	//var schrott_value = (JSON.parse(schrott)["schrott"]);
          var schrott_value = schrott["schrott"];
        	var schrott_percent = schrott_value*100;
          var schrott_grenze = schrott['Wahrscheinlickeitsgrenze'];
          var grenze_percent = schrott_grenze*100
        	console.log(data);
        	if (data.label == 'Identifikation 110'){
        	 	$('#detailcolumn .instance').append($('<br> <table class="station-id"><tbody><tr><td>Verschrottungswahrscheinlichkeit:</td><td> '
            + schrott_percent.toFixed(2)
            + '%</td></tr><tr><td>Status lt. Daten:</td><td>' + schrott['tatsächlicher Status']
            + '</td></tr><tr><td>Vorhersage: </td><td>' + schrott['Vorhersage'] + ' (Grenze von ' + grenze_percent.toFixed(2) + '%) '
            +'</tr></tbody></table>'));
        	}

        case 'position':
          // var data = JSON.parse($('event > notification',data).text());
          // if (data.unmark && data.at) {
          //   transitions.push({unmark: data.unmark[0], at: data.at[0]});
          //   transdraw();
          // }
          break;
        case 'activity':
          var data = JSON.parse($('event > notification',data).text());
          var activity = data.activity;
          var label = data.label;
          var station = label.match(/ ([\d\/-]+)$/)[1];
          if (station.split('/').length > 1) {
            station = station.split('/')[0];
            $(station.split('/')).each(function(k,val){
              acts[activity] = val;
            });
          } else {
            acts[activity] = station;
          }
          $('g.node[data-id=' + station + ']').addClass('active');
          transdraw2(station);
          $('#detailcolumn .stations').append($('<div class="station-id">' + station + '</div>'));
          break;
      }
    }
    if ($('vote > topic',data).length > 0) {
    }
  };
  ws.onclose = function() {
    console.log("monitoring", "closed", "server down i assume.");
  };
} //}}}

$(document).ready(function(){
  // $("#graphcolumn .draw").on('click','g.node',getnode);
  // $("#graphcolumn .draw").click('click',getpos);

  $.get("nodes.yaml", function(res) {
    var nodes = jsyaml.load(res);
    $(nodes).each(function(k,val){
      drawnode(val['ID'],val['X'],val['Y'],val['Name']);
    });
  });

  $.get("lines.yaml", function(res) {
    lines = jsyaml.load(res);
  });

  $('#run').click(function(){
    var value = $('#inumber').val();
    var jsonv = {radsatz: value};
    var value_json = JSON.stringify(jsonv);
    //var endpoint = "http://172.21.0.30/test.php?radsatz=" + value;
    //var jsonend = {read_me_out: endpoint};
    //var endpoint_json = JSON.stringify(jsonend);
    console.log('Here it comes');
    console.log(value);
    $('#detailcolumn .stations').empty();
    $('#graphcolumn .draw .lines').empty();
    $('#graphcolumn .draw .texts g.node.active').removeClass('active');
    $.ajax({
      type: "POST",
      //url: "http://localhost:9090/cpee-cockpit/start/instantiation",
      // url: "http://localhost:8080/testsets/Concurrent.xml"
      //url: "centurio.loc:9090/cpee-cockpit/testsets/Fulltest_3.6.xml"
      //Url: "http://172.21.0.30/cpee-cockpit/testsets/Fulltest_3.6.xml"
      url: 'http://localhost:9296/url',
      data: { info: "OEBB Sim", behavior: "fork_ready", url: "http://172.18.0.30/cpee-cockpit/testsets/Fulltest_3.6.xml", init: value_json},
      success: function(url){
        console.log(url);
        url = url['CPEE-INSTANCE-URL'];
        $('#detailcolumn .instance').show();
        $('#detailcolumn .instance a').text(url);
        $('#detailcolumn .instance a').attr('href','http://localhost:9090/cpee-cockpit/?monitor=' + url);
        $('body').attr('current-instance',url);
        $.ajax({
          type: "POST",
          url: url + "/notifications/subscriptions/",
          data: sub,
          success: function(res){
            res = res.unserialize();
            $.each(res,function(a,b){
              if (b[0] == 'key') {
                subscription = b[1];
              }
            });
            websocket();
          }
        });
      }
    });
  });
});
