import {
  select,
  csv,
  scaleLinear,
  scaleTime,
  extent,
  axisLeft,
  axisBottom,
  area,
  curveBasis
} from 'd3';

const svg = select('svg');
const height = +svg.attr('height'),
  width = +svg.attr('width');

const render = (data) => {
  const title = 'Legend';

  const xValue = (d) => d.year;
  const xAxisLabel = 'Time';

  const yValue = (d) => d.points;
  const yAxisLabel = 'Points';

  const margin = {
    top: 60,
    right: 40,
    bottom: 88,
    left: 100,
  };
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;

  const xScale = scaleTime()
    .domain(extent(data, xValue))
    .range([0, innerWidth])

  const yScale = scaleLinear()
    .domain(extent(data, yValue))
    .range([innerHeight, 0])
    .nice();

  const g = svg
    .append('g')
    .attr(
      'transform',
      `translate(${margin.left}, ${margin.top})`
    );

  const xAxis = axisBottom(xScale)
		.ticks(10)
    .tickSize(-innerHeight)
    .tickPadding(25);

  const yAxis = axisLeft(yScale)
    .tickSize(-innerWidth)
    .tickPadding(10);

  const yAxisG = g.append('g').call(yAxis);

  yAxisG.selectAll('.domain').remove();

  yAxisG
    .append('text')
    .attr('class', 'axis-label')
    .attr('y', -40)
    .attr('x', -innerHeight / 2)
    .attr('text-anchor', 'middle')
    .attr('transform', `rotate(-90)`)
    .text(yAxisLabel);

  const xAxisG = g
    .append('g')
    .call(xAxis)
    .attr('transform', `translate(0, ${innerHeight})`);

  xAxisG.select('.domain').remove();
  xAxisG
    .append('text')
    .attr('class', 'axis-label')
    .attr('y', 85)
  .attr('text-anchor', 'middle')
    .attr('x', innerWidth / 2)
    .text(xAxisLabel);
  
  const areaGenerator = area()
  	.x(d => xScale(xValue(d)))
  	.y0(innerHeight)
  	.y1(d => yScale(yValue(d)))
  	.curve(curveBasis)
  
  g.append('path')
  	.attr('d', areaGenerator(data))
    .attr('class', 'area-path')
  	
  g.append('text')
    .attr('class', 'title')
    .attr('y', -10)
    .text(title);
};

csv(
  'drose.csv'
).then((data) => {
  data.forEach((d) => {
    d.year = new Date(d.year)
    d.points = +d.points
  });
  render(data);
});