// adapt the d3 time scale to add discontinuities, so that weekends are removed
const xScale = fc.scaleDiscontinuous(d3.scaleTime())
  .discontinuityProvider(fc.discontinuitySkipWeekends());

const yScale = d3.scaleLinear();

// a candlestick series, by default it expects the provided data to have open, low, high, close, date properties
const candlestickSeries = fc.seriesSvgCandlestick()
	.bandwidth(2)
	.xScale(xScale)
	.yScale(yScale);

const xAxis = d3.axisBottom()
	.scale(xScale);
const yAxis = d3.axisLeft()
	.scale(yScale);

// use the extent component to determine the x and y domain
const xExtent = fc.extentDate()
	.accessors([d => d.date]);

const yExtent = fc.extentLinear()
	.accessors([d => d.high, d => d.low]);

const parseDate = d3.timeParse("%d-%b-%y");

d3.select('#plot-area')
  // handle the plot area measure event in order to determine the axis range
  .on('measure', () => {
     xScale.range([0, event.detail.width]);
     yScale.range([event.detail.height, 0]);
  })
  // handle the draw event, rendering the series
	.on('draw', (d, i, nodes) => {
     d3.select(nodes[i])
      .select('svg')
      .call(candlestickSeries);
  });

// handle the x-axis draw event, rendering the axis
d3.select('#x-axis')
  .on('draw', (d, i, nodes) => {
     d3.select(nodes[i])
      .select('svg')
      .call(xAxis);
  });

d3.select('#y-axis')
  // handle the y-axis measure event in order to offset the SVG to the left
  .on('measure', (d, i, nodes) => {
    const { width, height } = event.detail;
    d3.select(nodes[i])
      .select('svg')
      .attr('viewBox', `${-width} 0 ${width} ${height}`);
  })
  // handle the draw event, rendering the axis
  .on('draw', (d, i, nodes) => {
    d3.select(nodes[i])
      .select('svg')
      .call(yAxis);
  });


d3.csv('data.csv',
  // transform the data to use the default candlestick series properties
  row => ({
  	open: row.Open,
  	close: row.Close,
  	high: row.High,
  	low: row.Low,
  	date: parseDate(row.Date)
	}),
 	(error, data) => {
      	
    xScale.domain(xExtent(data));
    yScale.domain(yExtent(data));
    
  	// add the data to the plot area element
  	d3.select('#plot-area')
     	.datum(data)
  
    // render
    d3.select('#zoom-chart')
    	.node()
    	.requestRedraw();
});