function PieDrawer(selector) {
  this.selector = selector;
};
PieDrawer.width = 150;
PieDrawer.height = 150;
PieDrawer.radius = Math.min(PieDrawer.width, PieDrawer.height) / 2;
PieDrawer.formatPercent = d3.format(".2%");

PieDrawer.color_nos_oignons = "#ffa430";
PieDrawer.color_others = "#57075f";

PieDrawer.arc = d3.svg.arc()
    .outerRadius(PieDrawer.radius - 10)
    .innerRadius(PieDrawer.radius - 40);

PieDrawer.labelRadius = PieDrawer.radius - 15;

PieDrawer.pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.frac; });

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

PieDrawer.prototype.getFieldName = undefined;
PieDrawer.prototype.getField = undefined;
PieDrawer.prototype.draw = function() {
  var svg = d3.select(this.selector).append("svg")
      .style("margin", "auto")
      .attr("width", PieDrawer.width)
      .attr("height", PieDrawer.height)
    .append("g")
      .attr("transform", "translate(" + PieDrawer.width / 2 + "," + PieDrawer.height / 2 + ")");

  var text = svg.append("text")
      .attr("text-anchor", "middle")
      .attr("dy", ".35em")
      .text(L10n.loading);

  var field_getter = this.getField;
  d3.json(PieDrawer.onionoo_url + "&fields=fingerprint," + this.getFieldName(), function(error, raw_data) {
    var frac_nos_oignons = 0;
    raw_data['relays'].forEach(function(d) {
      nos_oignons_relays.forEach(function(r) {
        if (r.fingerprint == d.fingerprint) {
          var value = field_getter(d);
          if (value) {
            frac_nos_oignons += value;
          }
        }
      });
    });
    var frac_others = 1 - frac_nos_oignons;

    data = [ { name: L10n.nos_oignons, frac: frac_nos_oignons, color: PieDrawer.color_nos_oignons, },
             { name: L10n.others,      frac: frac_others,      color: PieDrawer.color_others }, ];

    text.text(PieDrawer.formatPercent(data[0].frac));

    var g = svg.selectAll(".arc")
        .data(PieDrawer.pie(data))
      .enter().append("g")
        .attr("class", "arc");

    g.append("path")
        .attr("d", PieDrawer.arc)
        .style("fill", function(d) { return d.data.color; });

  });
}

function ConsensusPieDrawer(selector) {
  this.selector = selector;
};
ConsensusPieDrawer.prototype = new PieDrawer();
ConsensusPieDrawer.prototype.getSelector = function() {
  return "#consensus-pie";
};
ConsensusPieDrawer.prototype.getFieldName = function() {
  return "consensus_weight_fraction";
};
ConsensusPieDrawer.prototype.getField = function(r) {
  return r.consensus_weight_fraction;
};

function ExitPieDrawer(selector) {
  this.selector = selector;
};
ExitPieDrawer.prototype = new PieDrawer();
ExitPieDrawer.prototype.getFieldName = function() {
  return "exit_probability";
};
ExitPieDrawer.prototype.getField = function(r) {
  return r.exit_probability;
};
