if(typeof demoData === "undefined"){
  demoData = {};
}
if(typeof(Monitor) === "undefined") {
  Monitor = {};
}

 (function(){

   Date.prototype.setISO8601 = function(dString){

   var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/;

   if (dString.toString().match(new RegExp(regexp))) {
   var d = dString.match(new RegExp(regexp));
   var offset = 0;

   this.setUTCDate(1);
   this.setUTCFullYear(parseInt(d[1],10));
   this.setUTCMonth(parseInt(d[3],10) - 1);
   this.setUTCDate(parseInt(d[5],10));
   this.setUTCHours(parseInt(d[7],10));
   this.setUTCMinutes(parseInt(d[9],10));
   this.setUTCSeconds(parseInt(d[11],10));
   if (d[12])
   this.setUTCMilliseconds(parseFloat(d[12]) * 1000);
   else
   this.setUTCMilliseconds(0);
   if (d[13] != 'Z') {
   offset = (d[15] * 60) + parseInt(d[17],10);
   offset *= ((d[14] == '-') ? -1 : 1);
   this.setTime(this.getTime() - offset * 60 * 1000);
   }
   }
   else {
     this.setTime(Date.parse(dString));
   }
    return this;
   };

})();


Monitor.Overview = {

  data: demoData,

  display: function(){

      var that = this, $tbody = $('#api-overview tbody'), method, $row;

      // var from = (function(){
      //     var now = Date.new(),
      //         year = now.getFullYear(),
      //         month = now.getMonth(),
      //         day   = now.getDate(),


      // })();

      $.getJSON("/admin/services/" + ThreeScale.service_id + "/monitor/events.json",function(data){
      for (var method, i = data.methods.length - 1; i >= 0; i--){
        method = data.methods[i];
        $row = $(that.row(method));
        if(i%2 != 0) {
          $row.addClass('odd');
        }

        $tbody.append($row);
      };

      $.getJSON("/admin/services/" + ThreeScale.service_id + "/monitor/response_times.json",function(data){
        for (var i = data.methods.length - 1; i >= 0; i--){
          method = data.methods[i];
          row = $tbody.find("tr[data-method='"+method.name+"']");
          row.find("td.response-time").html(parseInt(method.values["Global"][0]) + " ms");
        };

        $("#loading").fadeOut();
        $("table#api-overview").fadeIn();
      });
    });


  },

  responseTime: function(values){
    values = values.reverse().slice(1,2);
    return parseInt(values.sum() / 24);
  },

  friendly_status: function(status){
    var string;
    switch(status){
      case "up":
        string = "Service is operating normally";
        break;
      case "problems":
        string =  "Service is experiencing problems";
        break;
      case "down":
        string =  "Serivce is down";
        break;
      default:
        string = "N/A";
    }

    return string;
  },

  row: function(method){

    var cells;
    cells = ["<tr data-method='"+ method.name +"'>",
      "<td><span data-value class='method-name "+method.status+"'>", method.name,
      "</span></td>",
      "<td>", this.friendly_status(method.status), "</td>",
      "<td class='response-time'></td>"];
      // for (var i=0, x; i < method.values.length; i++) {
      //   x = method.values[i];
      //   cells.push("<td><span data-value='Uptime: "+ x +"%' class='status'>"+x+"%</span></td>");
      // };
      //
    cells.push("</tr>");
    return $(cells.join(""));
  },


}

Monitor.Uptime = {

  data: null,


  row: function(method){
    var cells;
    cells = ["<tr>",
      "<td><span class='method-name'>", method.name,
      "</span></td>"];
      for (var i=0, x; i < method.values.length; i++) {
        x = method.values[i];
        cells.push("<td><span data-value='Uptime: "+ x +"%' class='status'>"+x+"%</span></td>");
      };

    cells.push("</tr>");
    return $(cells.join(""));
  },

  insertIcons: function(){
    $('table#api-status tr td span.status').each(function(){

      // Cache element
      $this = $(this);

      // Bind tooltip
      $this.tipsy({title: 'data-value'});

      // Convernt string value to integer
      value = parseInt($this.html());

      // Decide which coloured icon to display

      state = 'green'
      if(value < 40){
        state = 'red';
      } else if(value < 100) {
        state = 'yellow'
      }

      // Update background
      $this.css('background-image', 'url(/assets/monitor/' + state + '.png)').html('');
    });
    $('table#api-status').fadeIn();
  },


  generateHeading: function(){
      var d = new Date(), since, days, cells = [];

      cells.push("<th>Method</th>");

      days = this.data.methods[0].values.length;

      since = this.data.period.since;
      since = d.setISO8601(since);

      new Date(d.setDate(d.getDate() + 1)).getMonth()

      for (var newDate, i=0; i < 8; i++) {
        newDate = new Date(+since + (i * 86400 * 1000));
        cells.push(["<th class='date'>", newDate.getDate(), " ", ThreeScale.Helper.General.months[newDate.getMonth()], "</th>"].join(''));
      };

      return cells.join("");
  },

  display: function(){

    var that = this, $row, method;
    $.getJSON("/admin/services/" + ThreeScale.service_id + "/monitor/uptimes.json",function(data){
      $("#loading").fadeOut();
      that.data = data;
      $tbody = $('#api-status tbody');
      $thead = $('#api-status thead');

      $thead.append(that.generateHeading());

      for (var i = that.data.methods.length - 1; i >= 0; i--){
        method = that.data.methods[i];
        $row = that.row(method);

        if(i%2 != 0) {
          $row.addClass('odd');
        }

        $tbody.append($row);
      };
      that.insertIcons();
      $('#uptime-keys').fadeIn();
    })

  }

}

Monitor.Response = {
        display: function(){
          var that = this, elements = ["#methods-menu", "#chart-keys"];
          $.getJSON("/admin/services/" + ThreeScale.service_id + "/monitor/response_times.json",function(data){
            $("#loading").fadeOut();
            that.data = data;
            that.displayMethodsMenu();
            that.setChart();
            that.watchRegionsKeys();
            $('#methods-menu ul li:first').trigger('click');

            for (var i=0; i < elements.length; i++) {
              $(elements[i]).fadeIn();
            };
          })
        },

        chart: null,

        data: function(){
          return this.data;
        },
        values: {},

        displayMethodsMenu: function(){
          var $list = $('#methods-menu ul'), item, that = this, method;
          for (var i = this.data.methods.length - 1; i >= 0; i--){
            method = this.data.methods[i];
            $item = $(["<li>", method.name, "</li>"].join(""));
            this.values.EU = method.values["EU"];
            this.values.US = method.values["US"];
            this.values.Global = method.values["Global"];
            $list.append($item);
          };

          $list.find('li').first().addClass('current');

          $list.find('li').click(function(){
            var $this = $(this);
            $list.find('li').removeClass('current');
            $this.addClass('current');
            that.displayMethod($this.html());
          });


          return $list;
        },

        regions: ["Global", "EU", "US"],

        valuesForMethod: function(method){
          for (var i = this.data.methods.length - 1; i >= 0; i--){
            if(this.data.methods[i].name == method){
              window.omar = this.data.methods;
              return this.data.methods[i].values;
            }
          };
          return null;
        },

        displayMethod: function(method){
          var values;
          for (var i=0; i < this.regions.length; i++) {
            values = this.valuesForMethod(method);
            window.values = values;
            this.setData(this.chart.series[i], values[this.regions[i]].slice(0,-1));
          };

          this.chart.redraw();
        },

        setData: function(series, data){
          series.setData(data, false);
        },

        watchRegionsKeys: function(){
          var $this,
              region,
              series,
              seriesSet = this.chart.series,
              that = this;

          $("#chart-keys span").click(function(){
            $this = $(this);
            region = $this.attr('data-value');

            for (var i=0; i < seriesSet.length; i++) {
              series = seriesSet[i];
              if(series.name == region){
                if(series.visible){
                  series.hide();
                  $this.addClass("hidden");
                } else {
                  series.show();
                  $this.removeClass("hidden");
                }
                break;
              }
            };

          });
        },

        setChart: function(){

          Highcharts.setOptions(Monitor.Charts.Theme);
            this.chart = new Highcharts.Chart({
               chart: {
                  ignoreHiddenSeries: true,
                  renderTo: 'chart',
                  defaultSeriesType: 'line',
                  spacingTop: 40,
                  spacingLeft: 20,
                  spacingRight: 20,
                  spacingBottom: 20
               },

               title: {
                  text: null
               },

               plotOptions : {
                 series : {
                    pointStart: +new Date().setISO8601(this.data.period.since),
                    lineWidth: 2,
                    marker: {radius: 0},
                    pointInterval : 3600 * 1000 // 1 Hour
                 }
               },

               yAxis: {
                  title: {
                     text: null
                  }
               },
               series: [{name: 'Global'},{name: 'EU'},{name: 'US'}]
            });

        }

};

Monitor.Charts = {};
Monitor.Charts.Theme = {
  colors: ['#0077CC', '#B23600', '#FF8A00'],
  chart: {
    borderColor: '#ddd',
    borderWidth: 2,
    plotBorderColor: '#CCCCCC'
  },
  credits: {enabled: false},
  xAxis: {
      type: 'datetime'
  },
  yAxis: {
      title: {enabled: false},
      lineWidth: 1,
      min: 0,
      minPadding: 0,
      gridLineWidth: 1,
      tickWidth: 0,
      gridLineColor: '#e7e7e7',
      lineColor: '#e7e7e7',
      tickColor: '#e7e7e7',
      labels: {
        enabled: true
      }
  },
  legend: {
    enabled : false,
  },

  tooltip: {
      backgroundColor: {
        linearGradient: [0, 0, 0, 50],
        stops: [
          [0, 'rgba(66, 60, 50, .9)'],
          [1, 'rgba(29, 27, 21, .8)']
        ]
      },
      borderWidth: 0,
      style: {
        color: '#FFF'
      },
      formatter: function(){
        return ['<strong>', this.series.name, "<strong><br/>", Highcharts.dateFormat('%d %b %I:%M%p', this.x), "<br/>",
                Highcharts.numberFormat(this.y, 0), " ms"].join("");
      }
    },

  plotOptions: {
      series: {
          fillColor: '#E6F2FA',
          lineWidth: 3,
          animation: false,
          shadow: false,
          marker: {
            lineWidth: 1,
            radius: 4
          }
      }
  }

};
