import {
  select,
  csv,
  scaleLinear,
  max,
  scaleBand,
  axisLeft,
  axisBottom,
  format
} from 'd3';

const titleText = 'Highest Scoring performance';
const xAxisLabelText = 'points';

const svg = select('svg');

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

let getXvalue = function(d){
 return d['points'];
};

let getyvalue = function(d){
 return d.player;
};

const render = data => {
  const xValue = getXvalue;
  const yValue = getyvalue
  const margin = { top: 50, right: 50, bottom: 77, left: 210 };
  const innerWidth = width - (margin.left + margin.right);
  const innerHeight = height -( margin.top + margin.bottom);
  
  const xScale   = scaleLinear()
    .domain([40, max(data, xValue)])//space of white space
    .range([0, innerWidth]);//space of red lines
  
  const yScale = scaleBand()
    .domain(data.map(yValue))//just shows every value
    .range([0, innerHeight])//space of red lines vertical
    .padding(0.1);
  
  const g = svg.append('g')
    .attr('transform', `translate(${margin.left},${margin.top})`);
  //44 to 45 just makes enough space for ticks
  
  const xAxisTickFormat = number =>//formatting xaxis ticks
    format(10, "+f")(number);
      
  
  const xAxis = axisBottom(xScale)
    .tickFormat(xAxisTickFormat)
    .tickSize(-innerHeight);// lines go uptil top of graph
  
  g.append('g')//take out the tick line from vertical
    .call(axisLeft(yScale))
    .selectAll('.domain, .tick line')
      .remove();
  
  const xAxisG = g.append('g').call(xAxis)
    .attr('transform', `translate(0,${innerHeight})`);
  
  xAxisG.select('.domain')//removes x line 
    .remove();
  
  xAxisG.append('text')
      .attr('class', 'axis-label')
      .attr('y', 55)//size y margin?
      .attr('x', innerWidth / 2)//size x margin?
      .text(xAxisLabelText);
  
  g.selectAll('rect').data(data)
    .enter().append('rect')
      .attr('y', d => yScale(yValue(d)))//gets values right position y
      .attr('width', d => xScale(xValue(d)))//gets values right position x
      .attr('height', yScale.bandwidth());//box size
  
  g.append('text')
      .attr('class', 'title')
      .attr('y', -10)
      .text(titleText);
};

csv('data.csv').then(data => {
  render(data);
});