/* global d3 */

// D3 convention: define margin as an object called margin with these props:
let margin = {
  top: 10,
  right: 20,
  bottom: 30,
  left: 30
};
let width = 400 - margin.left - margin.right;
let height = 600 - margin.top - margin.bottom;

/**
 * Adjust SVG size.
 *
 * @param {Selection} svg
 *   An SVG D3 selection.
 *
 * @return {void}
 */
function responsivefy(svg) {
  // get container + svg aspect ratio.
  // node() returns the raw DOM node -> parentNode returns the div.chart.
  const container = d3.select(svg.node().parentNode);
  const width = parseInt(svg.style("width"), 10);
  const height = parseInt(svg.style("height"), 10);
  const aspect = width / height;

  // Get width of container and resize SVG to fit it.
  function resize() {
    let targetWidth = parseInt(container.style("width"), 10);
    svg.attr("width", targetWidth);
    svg.attr("height", Math.round(targetWidth / aspect));
  }

  // Add viewBox and preserveAspectRatio properties,
  // and call resize to that svg resizes on initial page load
  svg.attr("viewBox", "0 0 " + width + " " + height)
    .attr("preserveAspectRatio", "xMinYMid")
    .call(resize);

  // To register multiple listeners for the same event type,
  // you need to add namespace, i.e. 'click.foo'
  // necessary if you call invoke this function for multiples SVGs
  // api docs: https://github.com/mbostock/d3/wiki/Selections#on
  d3.select(window)
    .on("resize." + container.attr("id"), resize);
}

let svg = d3.select('.chart')
  .append('svg')
    // Match the size of the chart-containing <div> with the viewport.
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
    .call(responsivefy)
    .append('g')
    .attr('transform', () => `translate(${margin.left},${margin.top})`);
// Everything below this line no longer needs to care about margins.

// At this point, the "svg" variable actually contains the <g> selection.
svg.append('rect')
  .attr('width', width)
  .attr('height', height)
  .style('fill', 'lightblue')
  .style('stroke', 'green');

let yScale = d3.scaleLinear()
  .domain([0, 100])
  // reversed because SVG coordinates are top to bottom.
  .range([height, 0]);

let yAxis = d3.axisLeft(yScale);
svg.call(yAxis);

let xScale = d3.scaleTime()
  .domain([new Date(2016, 0, 1, 6), new Date(2016, 0, 1, 9)])
  .range([0, width]);

let xAxis = d3.axisBottom(xScale)
  .ticks(5)
  .tickSize(10)
  .tickPadding(5);

svg.append('g')
  .attr('transform', `translate(0, ${height})`)
  .call(xAxis);