function BwDrawer(selector) {
  this.selector = selector;
};
BwDrawer.prototype = new BwDrawer();

BwDrawer.margin = {top: 50, right: 10, bottom: 90, left: 130};
BwDrawer.width = 600 - BwDrawer.margin.left - BwDrawer.margin.right;
BwDrawer.height = 400 - BwDrawer.margin.top - BwDrawer.margin.bottom;

BwDrawer.parseTime = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
BwDrawer.bwFormatter = d3.format(".f");

BwDrawer.x = d3.time.scale()
    .range([0, BwDrawer.width]);

BwDrawer.y = d3.scale.linear()
    .range([BwDrawer.height, 0]);

BwDrawer.color = d3.scale.category20();

BwDrawer.xAxis = d3.svg.axis()
    .scale(BwDrawer.x)
    .orient("bottom");

BwDrawer.yAxis = d3.svg.axis()
    .scale(BwDrawer.y)
    .orient("left")
    .tickFormat(function(d) { return (d == 0) ? "" : BwDrawer.bwFormatter(Math.abs(d)) + " Mbit/s " + ((d > 0) ? "in" : "out"); });

BwDrawer.area = d3.svg.area()
    .x(function(d) { return BwDrawer.x(d.date); })
    .y0(function(d) { return BwDrawer.y(d.y0); })
    .y1(function(d) { return BwDrawer.y(d.y0 + d.y); });

BwDrawer.read_stack = d3.layout.stack()
    .values(function(d) { return d.read_values; });
BwDrawer.write_stack = d3.layout.stack()
    .values(function(d) { return d.write_values; });

BwDrawer.onionoo_url = "https://onionoo.torproject.org/bandwidth?type=relay&contact=adminsys@nos-oignons.net";

BwDrawer.periods = [
    { id: "1_month", label: L10n.t_1_month },
    { id: "3_months", label: L10n.t_3_months },
    { id: "1_year", label: L10n.t_1_year },
  ];

BwDrawer.extract_values = function(history, interval, minTime, maxTime) {
  var values = [];
  var first = history ? BwDrawer.parseTime(history.first) : maxTime;
  var last = history ? BwDrawer.parseTime(history.last) : minTime;
  var i = 0;
  for (var current = minTime; current <= maxTime; current = d3.time.second.offset(current, interval)) {
    values.push({ date: current,
                  y: (first <= current && current <= last) ? history.factor * history.values[i++] * 8 / 1000000 : 0
                });
  }
  return values;
}

BwDrawer.draw_bandwidth_graph = function(raw_data, selector, period) {
  var update_period;

  var svg = d3.select(selector).append("svg")
      .attr("width", BwDrawer.width + BwDrawer.margin.left + BwDrawer.margin.right)
      .attr("height", BwDrawer.height + BwDrawer.margin.top + BwDrawer.margin.bottom)
    .append("g")
      .attr("transform", "translate(" + BwDrawer.margin.left + "," + BwDrawer.margin.top + ")");

  var form = d3.select(selector).append("form")
      .attr("action", "#");
  BwDrawer.periods.forEach(function(p) {
    var div = form.append("div");
    var radio = div.append("input")
      .attr("type", "radio")
      .attr("name", "period")
      .attr("id", "period_" + p.id)
      .on("click", function() { update_period(p.id); });
    div.append("label")
      .attr("for", "period_" + p.id)
      .text(p.label);
    if (p.id == BwDrawer.periods[0].id) {
      radio.attr("checked", true);
    }
  });

  var valid_fingerprints = [];
  nos_oignons_relays.forEach(function(r) {
    var relay_data = raw_data["relays"].filter(function(d) { return d.fingerprint == r.fingerprint; })[0];
    valid_fingerprints.push(r.fingerprint);
  });
  BwDrawer.color.domain(valid_fingerprints);

  var bw_data = {};
  BwDrawer.periods.map(function(p) { return p.id; }).forEach(function(period) {
    var interval = d3.max(raw_data.relays, function(d) {
      return d['read_history'][period] && d['read_history'][period].interval;
    });
    raw_data.relays.forEach(function(d) {
      if ((d['read_history'][period] && d['read_history'][period].interval != interval) ||
          (d['write_history'][period] && d['write_history'][period].interval != interval)) {
        throw "PANIC: Different interval for different relays in the same time period.";
      }
    });
    var minTime = d3.min(raw_data.relays, function(d) {
      return d['read_history'][period] && BwDrawer.parseTime(d['read_history'][period].first) &&
             d['write_history'][period] && BwDrawer.parseTime(d['write_history'][period].first);
    });
    var maxTime = d3.min(raw_data.relays, function(d) {
      return d['read_history'][period] && BwDrawer.parseTime(d['read_history'][period].last) &&
             d['write_history'][period] && BwDrawer.parseTime(d['write_history'][period].last);
    });

    var maxReadBandwidth = 0;
    var maxWriteBandwidth = 0;

    var values = BwDrawer.color.domain().map(function(fingerprint) {
      var relay_data = raw_data["relays"].filter(function(d) { return d.fingerprint == fingerprint; })[0];
      var read_history = relay_data['read_history'][period];
      var write_history = relay_data['write_history'][period];
      var read_values = BwDrawer.extract_values(read_history, interval, minTime, maxTime);
      var write_values = BwDrawer.extract_values(write_history, interval, minTime, maxTime);

      maxReadBandwidth = maxReadBandwidth + d3.max(read_values, function(d) { return d.y; });
      maxWriteBandwidth = maxWriteBandwidth + d3.max(write_values, function(d) { return d.y; });

      return {
        fingerprint: fingerprint,
        read_values: read_values,
        write_values: write_values.map(function(d) { d.y = -d.y; return d })
      };
    });
    bw_data[period] = { minTime: minTime,
                        maxTime: maxTime,
                        maxReadBandwidth: maxReadBandwidth,
                        maxWriteBandwidth: maxWriteBandwidth,
                        values: values };
  });

  BwDrawer.y.domain([-d3.max(d3.values(bw_data), function(d) { return d.maxWriteBandwidth; }),
            d3.max(d3.values(bw_data), function(d) { return d.maxReadBandwidth; })]);

  var initial_period = BwDrawer.periods[0].id;

  BwDrawer.x.domain([bw_data[initial_period].minTime, bw_data[initial_period].maxTime]);

  var read_graph = svg.selectAll(".read_graph")
      .data(BwDrawer.read_stack(bw_data[initial_period].values))
    .enter().append("path")
      .attr("class", "read_graph area")
      .attr("d", function(d) { return BwDrawer.area(d.read_values); })
      .style("fill", function(d) { return BwDrawer.color(d.fingerprint); });

  var write_graph = svg.selectAll(".write_graph")
      .data(BwDrawer.write_stack(bw_data[initial_period].values))
    .enter().append("path")
      .attr("class", "write_graph area")
      .attr("d", function(d) { return BwDrawer.area(d.write_values); })
      .style("fill", function(d) { return BwDrawer.color(d.fingerprint); });

  update_period = function(period) {
    BwDrawer.x.domain([bw_data[period].minTime, bw_data[period].maxTime]);
    var t = svg.transition().duration(300);
    t.select(".x.axis").call(BwDrawer.xAxis);
    t.selectAll(".read_graph").style("fill-opacity", 0);
    t.selectAll(".write_graph").style("fill-opacity", 0);
    t.each("end", function() {
      d3.selectAll(".read_graph").data(BwDrawer.read_stack(bw_data[period].values));
      d3.selectAll(".write_graph").data(BwDrawer.write_stack(bw_data[period].values));
      d3.selectAll(".read_graph").attr("d", function(d) { return BwDrawer.area(d.read_values); })
      d3.selectAll(".write_graph")
        .attr("d", function(d) { return BwDrawer.area(d.write_values); })
      var t2 = svg.transition().duration(100);
      t2.selectAll(".read_graph").style("fill-opacity", 1);
      t2.selectAll(".write_graph").style("fill-opacity", 1);
    });
    d3.selectAll(".x.axis text")
      .style("text-anchor", "end")
      .attr("transform", "rotate(-90) translate(-10, 0)");
  }

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + BwDrawer.height + ")")
      .call(BwDrawer.xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("transform", "rotate(-90) translate(-10, 0)");

  svg.append("g")
      .attr("class", "y axis")
      .call(BwDrawer.yAxis);

  var legend = svg.selectAll(".legend")
      .data(BwDrawer.color.domain().slice().reverse())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + ((i * 20) - BwDrawer.margin.top) + ")"; });

  legend.append("rect")
      .attr("x", BwDrawer.width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", BwDrawer.color);

  legend.append("text")
      .attr("x", BwDrawer.width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) {
        return nos_oignons_relays.filter(function(r) { return r.fingerprint == d; })[0].name;
      });
};

BwDrawer.prototype.draw = function() {
  var selector = this.selector;
  d3.json(BwDrawer.onionoo_url, function(error, raw_data) {
    d3.select(selector).text("");
    BwDrawer.draw_bandwidth_graph(raw_data, selector);
  });
};
