extends layout

block scripts
  script(type='text/javascript', src='cubism.v1.js')
  script(type='text/javascript', src='highlight.min.js')

block content
  div(style="margin-bottom: 12px")
  div(style="height:2px;")
    select#statsGraphSelect
      option(value="deltaPacketsPerSec") Packets/Sec
      option(value="deltaBytesPerSec") Bytes/Sec
      option(value="deltaBitsPerSec") Bits/Sec
      option(value="deltaSessionsPerSec") Sessions/Sec
      option(value="deltaDroppedPerSec") Dropped/Sec
      option(value="monitoring") Active Sessions
      option(value="freeSpaceM") Free Space
      option(value="memory") Memory
      option(value="cpu") CPU
      option(value="diskQueue") Disk Queue
  div#statsGraph
  table#stats(cellpadding="0",cellspacing="0",border="0",class="display",style="table { clear: both }")
    thead
      tr
        th
        th Node
        th Time
        th Packets Captured
        th Kilobytes Saved
        th Sessions Saved
        th Active Sessions
        th Free Space MB
        th Memory MB
        th CPU
        th Disk Queue
        th Packets / Sec
        th Bytes / Sec
        th Sessions / Sec
        th Drops / Sec
    tbody
    tfoot
      tr#avg
        th
        th Average
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
      tr#tot
        th
        th Total
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
        th
  br
  h1 Elasticsearch
  table#esstats(cellpadding="0",cellspacing="0",border="0",class="display",style="table { clear: both }")
    thead
      tr
        th Node
        th Documents
        th Disk Storage (MB)
        th Heap Size (MB)
        th OS Load
        th ES CPU (%)
        th Read/Sec (K)
        th Write/Sec (K)
        th Searches
    tbody
    tfoot
      tr#avges
        th Average
        th
        th
        th
        th
        th
        th
        th
        th
      tr#totes
        th Total
        th
        th
        th
        th
        th
        th
        th
        th
  br

  script(type='text/javascript').
    var statsTable;
    var esstatsTable;

    var context = cubism.context()
        .serverDelay(0)
        .clientDelay(0)
        .step(5e3)
        .size(1440);

    function makeStatsGraph(metricName) {
      function metric(name) {
        return context.metric(function(startV, stopV, stepV, callback) {
          $.ajax( {
            "dataType": 'json',
            "type": "GET",
            "url": "#{basePath}dstats.json?nodeName=" + name +
                          "&start=" + startV/1000 +
                          "&stop=" + stopV/1000 +
                          "&step=" + stepV/1000 +
                          "&interval=5" +
                          "&name=" + metricName,
            "success": function(data) {
              if (metricName === "cpu") {
                for (i = 0; i < data.length; i++) {
                  data[i] = data[i]/100.0;
                }
              }
              callback(null, data);
            }
          });
        }, name);
      }

      $("#statsGraph").empty();
      d3.select("#statsGraph").call(function(div) {
        var nodes = !{JSON.stringify(nodes)};
        var metrics = [];
        for (var i = 0, ilen = nodes.length; i < ilen; i++) {
          metrics.push(metric(nodes[i]));
        }

        div.append("div")
            .attr("class", "axis")
            .call(context.axis().orient("top"));

        div.selectAll(".horizon")
            .data(metrics)
          .enter().append("div")
            .attr("class", "horizon")
            .call(context.horizon());

        div.append("div")
            .attr("class", "rule")
            .call(context.rule());

      });
    }

    makeStatsGraph("deltaPackets");

    context.on("focus", function(i) {
        d3.selectAll(".value").style("right", i === null ? null : context.size() - i + "px");
    });


    $(document).ready(function() {
      statsTable = $('#stats').dataTable( {
        "oLanguage": {
          "sProcessing": "<img src=\"watching.gif\"><div class='blink'>I'm Hootin' :D</div>",
          "sLengthMenu": "_MENU_",
          "sInfo" : "Showing _START_ - _END_ of _TOTAL_",
          "sInfoFiltered" : "(_MAX_ total)"
        },
        "sDom": '<"H"lipr>t<"F"ip>',
        "iDisplayLength": 500,
        "aLengthMenu": [100, 500, 1000, 5000],
        "bRetrieve": true,
        "bFilter": false,
        "bScrollCollapse": true,
        "bAutoWidth": false,
        "aoColumns": [
          {
            "mDataProp" : "detail",
            "sWidth": "30",
            "bSortable": false,
            "sClass": "right"
          },
          { "mDataProp" : "id",
            "sClass": "right",
            "sType": "string"
          },
          { "mDataProp" : "currentTime",
            "fnRender" : function(oObj) {
              return dateString(oObj.aData.currentTime, " ");
            },
            "sClass": "right"
          },
          { "mDataProp" : "totalPackets",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "totalK",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "totalSessions",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "monitoring",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "freeSpaceM",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "memory",
            "fnRender" : function(oObj) {
              return numberWithCommas(Math.ceil(oObj.aData[oObj.mDataProp]/1000000));
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "cpu",
            "fnRender" : function(oObj) {
              return "" + oObj.aData[oObj.mDataProp]/100.0;
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "diskQueue",
            "fnRender" : function(oObj) {
              return numberWithCommas(Math.ceil(oObj.aData[oObj.mDataProp]));
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "deltaPacketsPerSec",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "deltaBytesPerSec",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "deltaSessionsPerSec",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "deltaDroppedPerSec",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          }
        ],
        "aaSorting": [[1, "asc"]],
        "fnFooterCallback": function ( nRow, aaData, iStart, iEnd, aiDisplay ) {
          var avgCells = $('tr#avg > th');
          var totCells = $('tr#tot > th');

          var totals = {totalPackets: 0, totalK: 0, totalSessions:0, deltaPacketsPerSec:0, deltaBytesPerSec:0 , deltaSessionsPerSec: 0, deltaDroppedPerSec: 0, monitoring: 0, memory: 0, cpu: 0, diskQueue: 0};
          for (var r = 0, rlen = aaData.length; r < rlen; r++) {
              totals.totalPackets += parseInt(aaData[r].totalPackets.replace(/\,/g,''), 10);
              totals.totalK += parseInt(aaData[r].totalK.replace(/\,/g,''), 10);
              totals.totalSessions += parseInt(aaData[r].totalSessions.replace(/\,/g,''), 10);

              totals.deltaDroppedPerSec += parseInt(aaData[r].deltaDroppedPerSec.replace(/\,/g,''), 10);
              totals.deltaSessionsPerSec += parseInt(aaData[r].deltaSessionsPerSec.replace(/\,/g,''), 10);
              totals.deltaPacketsPerSec += parseInt(aaData[r].deltaPacketsPerSec.replace(/\,/g,''), 10);
              totals.deltaBytesPerSec += parseInt(aaData[r].deltaBytesPerSec.replace(/\,/g,''), 10);
              totals.monitoring += parseInt(aaData[r].monitoring.replace(/\,/g,''), 10);
              totals.memory += parseInt(aaData[r].memory.replace(/\,/g,''), 10);
              totals.cpu += parseFloat(aaData[r].cpu.replace(/\,/g,''), 10)*100;
              totals.diskQueue += parseInt(aaData[r].diskQueue.replace(/\,/g,''), 10);
          }

          totCells[3].innerHTML = numberWithCommas(totals.totalPackets);
          totCells[4].innerHTML = numberWithCommas(totals.totalK);
          totCells[5].innerHTML = numberWithCommas(totals.totalSessions);
          totCells[6].innerHTML = numberWithCommas(totals.monitoring);
          totCells[8].innerHTML = numberWithCommas(totals.memory);
          totCells[9].innerHTML = "" + (totals.cpu/100.0);
          totCells[10].innerHTML = numberWithCommas(totals.diskQueue);
          totCells[11].innerHTML = numberWithCommas(totals.deltaPacketsPerSec);
          totCells[12].innerHTML = numberWithCommas(totals.deltaBytesPerSec);
          totCells[13].innerHTML = numberWithCommas(totals.deltaSessionsPerSec);
          totCells[14].innerHTML = numberWithCommas(totals.deltaDroppedPerSec);

          avgCells[3].innerHTML = numberWithCommas(Math.floor(totals.totalPackets/aaData.length));
          avgCells[4].innerHTML = numberWithCommas(Math.floor(totals.totalK/aaData.length));
          avgCells[5].innerHTML = numberWithCommas(Math.floor(totals.totalSessions/aaData.length));
          avgCells[6].innerHTML = numberWithCommas(Math.floor(totals.monitoring/aaData.length));
          avgCells[8].innerHTML = numberWithCommas(Math.floor(totals.memory/aaData.length));
          avgCells[9].innerHTML = "" + Math.floor(totals.cpu/aaData.length)/100;
          avgCells[10].innerHTML = numberWithCommas(Math.floor(totals.diskQueue/aaData.length));
          avgCells[11].innerHTML = numberWithCommas(Math.floor(totals.deltaPacketsPerSec/aaData.length));
          avgCells[12].innerHTML = numberWithCommas(Math.floor(totals.deltaBytesPerSec/aaData.length));
          avgCells[13].innerHTML = numberWithCommas(Math.floor(totals.deltaSessionsPerSec/aaData.length));
          avgCells[14].innerHTML = numberWithCommas(Math.floor(totals.deltaDroppedPerSec/aaData.length));
        }
      } );

      esstatsTable = $('#esstats').dataTable( {
        "oLanguage": {
          "sProcessing": "<img src=\"watching.gif\"><div class='blink'>I'm Hootin' :D</div>",
          "sLengthMenu": "_MENU_",
          "sInfo" : "Showing _START_ - _END_ of _TOTAL_",
          "sInfoFiltered" : "(_MAX_ total)"
        },
        "sDom": '<"H"lipr>t<"F"ip>',
        "iDisplayLength": 500,
        "aLengthMenu": [100, 500, 1000, 5000],
        "bRetrieve": true,
        "bFilter": false,
        "bScrollCollapse": true,
        "bAutoWidth": false,
        "aoColumns": [
          { "mDataProp" : "name",
            "sClass": "right",
            "sType": "string"
          },
          { "mDataProp" : "docs",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "storeSize",
            "fnRender" : function(oObj) {
              return numberWithCommas(Math.floor(oObj.aData[oObj.mDataProp]/1000000));
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "heapSize",
            "fnRender" : function(oObj) {
              return numberWithCommas(Math.floor(oObj.aData[oObj.mDataProp]/1000000));
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "load",
            "fnRender" : function(oObj) {
              return "[" + oObj.aData.load[0].toFixed(2) + ", " + oObj.aData.load[1].toFixed(2) + ", " + oObj.aData.load[2].toFixed(2) + "]";
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "cpu",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "read",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "write",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          },
          { "mDataProp" : "searches",
            "fnRender" : function(oObj) {
              return numberWithCommas(oObj.aData[oObj.mDataProp]);
            },
            "sClass": "right",
            "sType": "formatted-num"
          }
        ],
        "aaSorting": [[3, "desc"]],
        "fnFooterCallback": function ( nRow, aaData, iStart, iEnd, aiDisplay ) {
          var totals = {docs: 0, storeSize: 0, heapSize:0, load: [0,0,0], cpu:0, read:0, write:0, searches:0};
          for (var r = 0, rlen = aaData.length; r < rlen; r++) {
              totals.docs += parseInt(aaData[r].docs.replace(/\,/g,''), 10);
              totals.storeSize += parseInt(aaData[r].storeSize.replace(/\,/g,''), 10);
              totals.heapSize += parseInt(aaData[r].heapSize.replace(/\,/g,''), 10);
              totals.cpu += parseInt(aaData[r].cpu.replace(/\,/g,''), 10);
              totals.read += parseInt(aaData[r].read.replace(/\,/g,''), 10);
              totals.write += parseInt(aaData[r].write.replace(/\,/g,''), 10);
              totals.searches += parseInt(aaData[r].searches.replace(/\,/g,''), 10);
              var load = JSON.parse(aaData[r].load);
              totals.load[0] += load[0];
              totals.load[1] += load[1];
              totals.load[2] += load[2];
          }

          var avgCells = $('tr#avges > th');
          var totCells = $('tr#totes > th');

          $(totCells[1]).html(numberWithCommas(totals.docs));
          $(totCells[2]).html(numberWithCommas(totals.storeSize));
          $(totCells[3]).html(numberWithCommas(totals.heapSize));
          $(totCells[4]).html("[" + totals.load[0].toFixed(2) + ", " + totals.load[1].toFixed(2) + ", " + totals.load[2].toFixed(2) + "]");
          $(totCells[5]).html(numberWithCommas(totals.cpu));
          $(totCells[6]).html(numberWithCommas(totals.read));
          $(totCells[7]).html(numberWithCommas(totals.write));
          $(totCells[8]).html(numberWithCommas(totals.searches));

          $(avgCells[1]).html(numberWithCommas(Math.floor(totals.docs/aaData.length)));
          $(avgCells[2]).html(numberWithCommas(Math.floor(totals.storeSize/aaData.length)));
          $(avgCells[3]).html(numberWithCommas(Math.floor(totals.heapSize/aaData.length)));
          $(avgCells[4]).html("[" + (totals.load[0]/aaData.length).toFixed(2) + ", " + (totals.load[1]/aaData.length).toFixed(2) + ", " + (totals.load[2]/aaData.length).toFixed(2) + "]");
          $(avgCells[5]).html(numberWithCommas(Math.floor(totals.cpu/aaData.length)));
          $(avgCells[6]).html(numberWithCommas(Math.floor(totals.read/aaData.length)));
          $(avgCells[7]).html(numberWithCommas(Math.floor(totals.write/aaData.length)));
          $(avgCells[8]).html(numberWithCommas(Math.floor(totals.searches/aaData.length)));
        }
      } );

      $(document).on('click', '#stats tbody td img', function () {
        var nTr = this.parentNode.parentNode;
        var aData = statsTable.fnGetData( nTr );
        if ( this.src.match('details_close') )
        {
          this.src = "DataTables-1.9.1/examples/examples_support/details_open.png";
          statsTable.fnClose( nTr );
        }
        else
        {
          this.src = "DataTables-1.9.1/examples/examples_support/details_close.png";
          $.ajax( {
            "dataType": 'html',
            "type": "GET",
            "url": '#{basePath}' + aData.id + '/statsDetail',
            "success": function(data) {
              statsTable.fnOpen( nTr, data, 'details' );
            }
          } );

        }
      } );

      function reloadData() {
        $.ajax( {
          "dataType": 'json',
          "type": "GET",
          "url": '#{basePath}stats.json',
          "success": function(data) {
            var nNodes = statsTable.fnGetNodes();
            for (var i = 0, ilen = data.aaData.length; i < ilen; i++) {
              var found = false;
              for (var n = 0, nlen = nNodes.length; n < nlen; n++) {
                var id = statsTable.fnGetData(n, 1);
                if (id === data.aaData[i].id) {
                  found = true;
                  if (statsTable.fnIsOpen(nNodes[n])) {
                    data.aaData[i].detail = '<img src="DataTables-1.9.1/examples/examples_support/details_close.png" height="20px">';
                  } else {
                    data.aaData[i].detail = '<img src="DataTables-1.9.1/examples/examples_support/details_open.png" height="20px">';
                  }
                  statsTable.fnUpdate(data.aaData[i], n, 0, false, false);
                  break;
                }
              }
              if (!found) {
                data.aaData[i].detail = '<img src="DataTables-1.9.1/examples/examples_support/details_open.png" height="20px">';
                statsTable.fnAddData(data.aaData[i], false);
              }
            }
            statsTable.fnDraw();
          }
        } );

        $.ajax( {
          "dataType": 'json',
          "type": "GET",
          "url": '#{basePath}esstats.json',
          "success": function(data) {
            updateHealth(data.health);
            var nNodes = esstatsTable.fnGetNodes();
            for (var i = 0, ilen = data.aaData.length; i < ilen; i++) {
              var found = false;
              for (var n = 0, nlen = nNodes.length; n < nlen; n++) {
                var name = esstatsTable.fnGetData(n, 0);
                if (name === data.aaData[i].name) {
                  found = true;
                  esstatsTable.fnUpdate(data.aaData[i], n, 0, false, false);
                  break;
                }
              }
              if (!found) {
                esstatsTable.fnAddData(data.aaData[i], false);
              }
            }
            esstatsTable.fnDraw();
          }
        } );
      }

      $('#statsGraphSelect').change(function() {
        makeStatsGraph($('#statsGraphSelect').val());
        return false;
      });

      setInterval(reloadData, 5000);
      reloadData();
    } );
