import { h, render, Component } from 'preact'; // eslint-disable-line no-unused-vars
import d3Linegraph from '../../d3/main';
import * as d3 from 'd3';

// displays the current Graph Item depending on mode
export default class GraphItem extends Component {

  // update data and replace it depending on group
  updateData () {
    const options = {
      entries: this.props.dataSet.data,
      questionGroup: this.props.dataSet.gruppe,
      points: this.props.points,
      // TODO: define in database / "offline content" along with graph data
      xAxisUnit: 'Zeit (Quartal)',
      yAxisUnit: 'Gewinn in Millionen Euro'
    };

    if (this.props.dataSet.gruppe === 1 || this.props.dataSet.gruppe === 3) {
      options.konkurrent = this.props.dataSet.konkurrent.toUpperCase();
    }

    if (this.props.dataSet.gruppe === 3) {

      // Initial (selected) range
      // TODO: change api to reflect this (reference/selected/solution) structure *per graph*
      // TODO: add to documentation that reference range is hard coded here
      options.referenceRange = {
        lowerBound: 'Q1/2015',
        upperBound: 'Q4/2015'
      };

      // Solution range
      options.solutionRange = {
        lowerBound: this.props.dataSet.untereGrenze,
        upperBound: this.props.dataSet.obereGrenze,
        gradient: {
          min: this.props.dataSet.anstiegUntereGrenze,
          max: this.props.dataSet.anstiegObereGrenze
        }
      };
      options.setDataMethod = this.props.setData;
    }

    const draw = d3Linegraph().options(options); // create and initialise d3 base element

    this.container.innerHTML = ''; // clear container
    d3.select(this.container).call(draw); // call / run d3 base element
  }

  // LIFECYCLE methods
  componentDidMount () {
    this.updateData();
  }

  shouldComponentUpdate (nextProps) {
    const isQuestion = nextProps.chartMode === 'question';
    const isFirstGroup = nextProps.dataSet.gruppe === 1;
    const isNextQuestion = nextProps.currentQuestion !== this.props.currentQuestion;

    return (isQuestion && isFirstGroup) || isNextQuestion;
  }

  componentDidUpdate () {
    this.updateData();
  }

  // output entry point for d3js module
  render () {
    return (<div className="chart  chart--centered" ref={ elem => (this.container = elem) }></div>);
  }

}
