import { h, render, Component } from 'preact'; // eslint-disable-line no-unused-vars
import { generateKey } from '../../utilities/randomizer';
import animatedBar from '../../d3/bar';
import * as d3 from 'd3';

// vote component
export default class VoteItem extends Component {

  constructor (props) {
    super(props);
    this.key = generateKey('graph');
  }

  static get defaultProps () {
    return { width: 845 };
  }

  setData (props) {
    if (props.votesFraction !== undefined) { // eslint-disable-line
      const countup = animatedBar().options({
        startval: 0,
        endval: parseFloat(props.votesFraction),
        duration: 750,
        round: 100,
        width: props.width,
        classname: 'd3-increment',
        colors: [ '#E3E3E3', props.activeColor ],
        tag: 'p'
      });

      this.container.innerHTML = '';
      d3.select(this.container).call(countup);
    }
  }

  componentDidMount () {
    this.setData(this.props);
  }

  componentWillReceiveProps (nextProps) {
    if (JSON.stringify(nextProps) !== JSON.stringify(this.props)) {
      this.setData(nextProps);
    }
  }

  render () {
    return (
      <div className="vote__item" key={this.key}>
        <div className="vote__item__label">{this.props.label}</div>
        <div className="vote__item__graph" ref={ elem => (this.container = elem) }></div>
      </div>
    );
  }

}
