/**
 * metrics client user interface
 * By Joe Turgeon [http://arithmetric.com]
 * 1/21/2010
 */

var MetricsUIGraph = function (setNames, indexMin, indexMax, width, height) {
  var self = (this === window) ? {} : this;
  self.element = {};
  self.setNames = (typeof setNames === 'string') ? [setNames] : setNames;
  self.indexMin = indexMin;
  self.indexMax = indexMax;
  self.graph = false;
  self.width = width;
  self.height = height;
  self.buildElement();
  self.update();
  return self;
};

MetricsUIGraph.prototype.addGraph = function (setName) {
  var children = metricsData.getDataSetChildren(setName);
  if (children.length) {
    this.setNames = this.setNames.concat(children);
  }
  else {
    this.setNames.push(setName);
  }
  this.update();
};

MetricsUIGraph.prototype.buildElement = function () {
  this.element = $('<div class="ui-graph box" style="width:' + this.width + 'px;height:' + this.height + 'px;"><div class="ui-graph-titlebar"></div><canvas width="' + (this.width - 4) + '" height="' + (this.height - 20) + '"></canvas><div class="ui-graph-sidebar box"></div></div>');
  this.element.data('uiGraph', this);
  this.graph = new MetricsGraph($('canvas', this.element).get(0), this.setNames, this.indexMin, this.indexMax);
  this.graph.onUpdate = this;
};

MetricsUIGraph.prototype.getElement = function () {
  return this.element;
};

MetricsUIGraph.prototype.update = function () {
  if (this.graph && this.graph.update) {
    var cvs = $('canvas', this.element);
    if (cvs.width() !== (this.width - 4) || cvs.height() !== (this.height - 20)) {
      cvs.replaceWith('<canvas width="' + (this.width - 4) + '" height="' + (this.height - 20) + '"></canvas>');
      this.graph.cvs = $('canvas', this.element).get(0);
      this.graph.width = this.width;
      this.graph.height = this.height;
    }
    if (this.element.width() !== this.width || this.element.height() !== this.height) {
      this.element.width(this.width).height(this.height);
    }
    if (this.graph.setNames !== this.setNames) {
      this.graph.setNames = this.setNames;
    }
    this.graph.indexMin = this.indexMin;
    this.graph.indexMax = this.indexMax;
    this.graph.update();
    this.updateInterface();
  }
};

MetricsUIGraph.prototype.updateInterface = function () {
  var gamenu = $('.ui-graph-titlebar', this.element).empty();
  var num = this.setNames.length;
  var tab;
  for (var i = 0; i < num; i++) {
    tab = this.buildSetTab(this.setNames[i]);
    gamenu.append(tab);
  }
  var el = $('<div class="ui-graph-settab"><div class="ui-graph-tabtitle selectable">Add</div></div>');
  var self = this;
  $('.ui-graph-tabtitle', el).click(function (e) {metricsSetSelector.activate(self.addGraph, self);e.preventDefault();});
  gamenu.append(el);
  if (num) {
    el = $('<div class="ui-graph-settab"><div class="ui-graph-tabtitle selectable">Clear</div></div>');
    el.click(this.removeAllGraphs);
    gamenu.append(el);
  }
};

MetricsUIGraph.prototype.separateGraph = function (e) {
  var st = $(this).parents('.ui-graph-settab');
  var g = st.parents('.ui-graph').data('uiGraph');
  var setName = st.data('setName');
  if (g.setNames) {
    var idx = g.setNames.indexOf(setName);
    if (idx >= 0) {
      g.setNames.splice(idx, 1);
      metrics.newGraph(setName);
    }
  }
  g.graph.forcerefresh = true;
  g.update.call(g);
  e.preventDefault();
};

MetricsUIGraph.prototype.removeGraph = function (e) {
  var st = $(this).parents('.ui-graph-settab');
  var g = st.parents('.ui-graph').data('uiGraph');
  var setName = st.data('setName');
  if (g.setNames) {
    var idx = g.setNames.indexOf(setName);
    if (idx >= 0) {
      g.setNames.splice(idx, 1);
    }
  }
  g.graph.forcerefresh = true;
  g.update.call(g);
  if (!g.setNames.length) {
    metrics.checkGraphs();
  }
  e.preventDefault();
};

MetricsUIGraph.prototype.removeAllGraphs = function (e) {
  var g = $(this).parents('.ui-graph').data('uiGraph');
  if (g.setNames) {
    g.setNames = [];
    g.graph.setNames = g.setNames;
  }
  g.update.call(g);
  metrics.checkGraphs();
  e.preventDefault();
};

MetricsUIGraph.prototype.buildSetTab = function (setName) {
  var idx = this.setNames.indexOf(setName);
  var color = this.graph.setColors[idx % this.graph.setColors.length];
  var el = $('<div class="ui-graph-settab"><div class="ui-graph-tabtitle"><span class="set-name">' + setName.toUpperCase() + '</span> <span class="set-color-key" style="background-color: ' + color + ';">&nbsp;</span></div><div class="ui-graph-tabbody"><div class="set-title">' +  metricsData.getDataSetTitle(setName) + '</div><div class="set-controls"><span class="set-remove selectable">Remove</span></div><div class="set-summary"></div><div class="set-analysis"></div></div></div>');
  el.data('setName', setName);
  $('.ui-graph-tabbody .set-remove', el).click(this.removeGraph);
  if (this.setNames.length > 1) {
    $('.set-controls', el).append(' | <span class="set-separate selectable">Separate</span>');
    $('.ui-graph-tabbody .set-separate', el).click(this.separateGraph);
  }
  var data = this.graph.data[setName];
  if (data && data.stats) {
    var shtml = 'Min value: ' + this.graph.formatNumber(data.stats.valueMin) + ' (at ' + metricsDate.format_jd(data.stats.valueMinIndex) + ')<br/>Max value: ' + this.graph.formatNumber(data.stats.valueMax) + ' (at ' + metricsDate.format_jd(data.stats.valueMaxIndex) + ')<br/>Domain: ' + metricsDate.format_jd(data.stats.indexMin) + ' to ' + metricsDate.format_jd(data.stats.indexMax) + '<br/>';
    $('.ui-graph-tabbody .set-summary', el).html('<strong>Summary</strong><div>' + shtml + '</div>');
  }
  var anhtml = '';
  for (var ankey in MetricsDataAnalysis) {
    if (MetricsDataAnalysis.hasOwnProperty(ankey)) {
      var anchecked = this.graph.analysis == ankey ? 'checked' : '';
      anhtml += '<input type="radio" name="set_' + setName + '_analysis" value="' + ankey + '" ' + anchecked + '/> ' + MetricsDataAnalysis[ankey] + '<br/>';
    }
  }
  $('.ui-graph-tabbody .set-analysis', el).html('<strong>Analysis</strong><div>' + anhtml + '</div>');
  $('.ui-graph-tabbody .set-analysis input', el).click(function (e) {var g = $(this).parents('.ui-graph').data('uiGraph');g.graph.analysis = MetricsDataAnalysis.hasOwnProperty($(this).val()) ? $(this).val() : 'NONE';g.graph.update();});
  $('.ui-graph-tabbody', el).hide();
  el.hover(this.openTab, this.closeTab);
  return el;
};

MetricsUIGraph.prototype.openTab = function (e) {
  var st = $(this);
  var g = st.parents('.ui-graph').data('uiGraph');
  st.parents('.ui-graph-titlebar').css('z-index', 1);
  $('.ui-graph-tabtitle', st).css({'border-top': '1px solid #000', 'border-left': '1px solid #000', 'border-right': '1px solid #000'});
  $('span.set-name', st).css('text-decoration', 'underline');
  var tabbody = $('.ui-graph-tabbody', st);
  tabbody.show();
  if ((tabbody.offset().top + tabbody.height()) > $(window).height()) {
    $('.ui-graph-tabtitle', st).css({'border-top': 'none', 'border-bottom': '1px solid #000'});
    tabbody.css('top', -1 * tabbody.height() - 10);
  }
};

MetricsUIGraph.prototype.closeTab = function (e) {
  var st = $(this);
  var g = st.parents('.ui-graph').data('uiGraph');
  st.parents('.ui-graph-titlebar').css('z-index', 'auto');
  $('.ui-graph-tabtitle', st).css({'border': 'none'});
  $('span.set-name', st).css('text-decoration', 'none');
  $('.ui-graph-tabbody', st).hide();
};
