// The fancybox spinner has been bound to jQuery's ajaxStart (see application.js)
// Unbind it, since we don't need it for this view.
$(document).unbind('ajaxStart');

if(typeof ThreeScale.Analytics.Usage == "undefined"){
  ThreeScale.Analytics.Usage = {};
}

// Shortcut to helpers

// MAINTAINABILITY HELL - please don't make shortcuts
var co = ThreeScale.Analytics.Charts;
// MAINTAINABILITY HELL - please don't make shortcuts
var h = ThreeScale.Helper.Charts;


// requires jQuery
(function($){
// Override/mutate methods
co.prototype.dealWithResponse = function(r){
    var that = this;
    $('#usage-total').fadeOut(function(){
        $(this).html(Highcharts.numberFormat(r.total, 0) + " " + pluralize(r.metric.unit, r.total));
        $(this).fadeIn();
    });

    this.initialiseChart(r);
};

co.prototype.showLoading = function(){
  this.$renderTo.find('.loading').fadeIn('slow');
};


  ThreeScale.Analytics.Usage = {

      // MAINTAINABILITY HELL - please don't make shortcuts
      // label to helpers
      h: ThreeScale.Helper.General,

      myName: ThreeScale.Analytics.Usage.name,
      service_id: null,
      application_id: null,

      resources: {
        usage: function(){
          if(ThreeScale.Analytics.Usage.application_id){
            return '/stats/applications/' + ThreeScale.Analytics.Usage.application_id + '/usage.json?skip_change=true';
          } else {
            return '/stats/services/' + ThreeScale.Analytics.Usage.service_id + '/usage.json?skip_change=true';
          }
        },
        methods: function(){
          if(ThreeScale.Analytics.Usage.application_id){
            return '/stats/applications/' + ThreeScale.Analytics.Usage.application_id + '/summary.json';
          } else {
            return '/stats/services/' + ThreeScale.Analytics.Usage.service_id + '/summary.json';
          }
        }
      },

      init: function(){
        this.showMethods();

        var c = new ThreeScale.Analytics.Charts('chart-1', { dataEndPoint: this.resources.usage() });
        c.metricID = jQuery('#metric-selector ul li:first').attr('title');
        c.chartOptions.plotOptions.series.showInLegend = false;
        c.init();
        c.$loading = jQuery('.chart-wrap .loading');
        this.hitsMetricID = jQuery("#metric-selector ul li[data-hits='true']").attr('title');
        this.chart = c;
        this.updateCSVPath();

        this.listen();
        // Don't show methods. New data set overlay system required
      },

      pool: [],
      // TODO: refactor and cut into smaller methods
      cancelPool: function(){
        var aborting = this.pool;
        this.pool = [];
        $(aborting).each(function(idx, jqXHR) {
          jqXHR.abort();
        });
      },

      listen: function() {
          var that = this;

          jQuery('.stats-support .paginate a').live('click', function(){
            $('div.paginate a').removeClass('current');
            $this = $(this);
            var value = $(this).attr('data-value');
            $this.addClass('current');
            $('div#methods ul').css({marginTop:-value});

            return false;
          });

          $(window).bind('apply-selectors', function() {
            that.cancelPool();
              $('#methods').html('');
              $('.stats-support .paginate').remove();
              that.updateCSVPath();
              if(Stats.SearchOptions.metric_name == 'hits') {
                  that.showMethods();
              } else {
                $('.methods-loading').hide();
              }
          });

          jQuery('#methods li').live('click', function() {
              $this = jQuery(this);

              var id = $this.attr('data-metric'),
              series = that.chart.chart.get(id),
              $total = $this.find('small');

              if (series) {
                  if(series.visible){
                      series.hide();
                      $total.css('backgroundColor', '#F6F6F6');
                  } else {
                      series.show();
                      $total.css('background', $total.attr('data-colour'));
                  }
              } else {
                  var data = JSON.parse($this.attr('data-values'));
                  var colour = h.pickColour(that.chart.chart.series.length);

                  that.chart.addLineSeries({
                      name: $this.attr('data-metric-name'),
                      data: data,
                      lineColor: colour,
                      id: id,
                      marker: { fillColor: colour }
                  });

                  $total.css('backgroundColor', colour);
                  $total.attr('data-colour', colour);

                  return false;
            }
          });
      },

      updateCSVPath: function(){
        var link = $('.download-csv-button a');
        var url = this.resources.usage().replace('.json', '.csv') + "&" + $.param(this.chart.queryData());
        link.attr('href', url);
      },

      showMethods: function(){
        function compare(a,b) {
          if (a.name < b.name) return 1;
          if (a.name > b.name) return -1;
          return 0;
        }

          var that = this;
          $('.methods-loading').show();
          $.ajax({
            beforeSend: function(jq) { that.addToPool(jq); },
            complete: function(jq) {that.removeFromPool(jq); },
            data: Stats.SearchOptions,
            url: that.resources.methods(),
            success: function(response) {
              that.methodsToHtml(response);
              $(".methods-loading").fadeOut();
              $('#methods').fadeIn();
            },

            error: function(error) {
              $('#methods p.paginate, #methods ul').remove();
              $('#methods').append('Failed to get the method details.');
            }
          });
      },

      methodToHtml: function(method){
        var unit, total;
        total = Highcharts.numberFormat(method.total, 0);
        unit = pluralize(method.metric.unit, total);
        return ["<li data-metric-count='"+ method.total +"'data-metric-name='"+method.metric.name+"'  data-metric='"+method.metric.id+"'  title='Data for method "+ method.metric.name +"' data-values='["+ method.values + "]'>",

          method.metric.name,
          "<span>",
            "<small>",
              total + ' ' + unit,
            "</small>",
          "</span>",
        "</li>"].join('');
      },

      addToPool: function(jqXHR) { // before jQuery send the request we will push it to our array
        this.pool.push(jqXHR);
      },
      removeFromPool: function(jqXHR) { // when some of the requests completed it will splice from the array
              var index = this.pool.indexOf(jqXHR);
              if (index > -1) {
                this.pool.splice(index, 1);
              }
            },

      methodsToHtml: function(methods){
        $('#methods').html("<h2>Methods</h2><div class='data-sup-wrap'><ul></ul></div>");

        var that = this;
        var metricList = $('.data-sup-wrap > ul');
        var success = function(method){
          var liHtml = that.methodToHtml(method);
          // Add the method to the list sorted by 'metric-count'
          //
          // Iterates over all "li nodes"
          // if 'method.total' is greater than 'metric-count' then
          // insert the "li html" before that and break the iteration,
          // else append the "li html" at the end of the list.
          var added = false;
          metricList.children('li').each(function(index, li){
            li = $(li);
            if(method.total > parseInt(li.data('metric-count'))){
              li.before(liHtml);
              added = true;
              return false;
            }
          });

          if(!added){
            metricList.append(liHtml);
          }

        };
        var url = this.resources.usage();
        for (var i=0; i<methods.length; i++){
          var method = methods[i];
          var options = $.extend({}, Stats.SearchOptions, {metric_name: method.metric.system_name});
          $.ajax({
            beforeSend: function(jq) { that.addToPool(jq); },
            complete: function(jq) {  that.removeFromPool(jq); },
            data: options,
            url: url,
            success: success
          });
        }
      },

      resetMethods: function(){
      },

      getData: function(metric, fn){
          var that = this,
          params = this.chart.queryData();
          colour = h.pickColour(this.chart.chart.series.length);

          params.metric_id = metric;

          $.ajax({
              dataType: 'json',
              data: params,
              url: that.dataEndPoint,

              success: function(r) {

                  that.chart.addLineSeries({
                      name: r.metric_name,
                      data:r.data,
                      lineColor: colour,
                      id: r.metric_id,
                      marker: {fillColor: colour}
                  });
                  if(fn){
                      fn(r, colour);
                  }
              }
          });
      }
  };

})(jQuery);
