import React from 'react';

class SecurityContentChart extends React.Component {
  constructor(props) {
    super(props);
    this.chart = false;
  }

  componentDidMount() {
    this.initializeChart();
  }

  componentDidUpdate(prevProps) {
    if (this.props.symbol !== prevProps.symbol ||
        this.props.exchange !== prevProps.exchange ) {
      this.initializeChart();
    }
  }

  componentWillUnmount() {
    this.removeChart();
  }

  getId() {
    const { id } = this.props;
    return 'SecurityContentChart-' + id;
  }

  initializeChart() {
    // Make sure we aren't making extra charts
    this.removeChart();
    const chartId = this.getId();

    // $bz-green in style
    const upColor = '#50C773';
    // $bz-red in style
    const downColor = '#C75050';
    const exchange = this.props.exchange;

    let exchangeSymbol = this.props.symbol;
    if (exchange) {
      if (exchange === 'OTCMKTS') {
        exchangeSymbol = 'OTC:' + exchangeSymbol;
      } else {
        exchangeSymbol = exchange + ':' + exchangeSymbol;
      }
    }
    // Make a new chart and store it so it can be removed later
    this.chart = new TradingView.widget({ // eslint-disable-line new-cap
      container_id: chartId,
      autosize: true,
      // fixedMode: true,
      symbol: exchangeSymbol,
      interval: 'D',
      timezone: 'America/New_York',
      theme: 'White',
      style: '1',
      locale: 'en',
      toolbar_bg: '#ffffff',
      hotlist: false,
      hideideas: true,
      hideideasbutton: true,
      // save_image: false,
      overrides: {
        'mainSeriesProperties.candleStyle.upColor': upColor,
        'mainSeriesProperties.candleStyle.downColor': downColor,
        'mainSeriesProperties.hollowCandleStyle.upColor': upColor,
        'mainSeriesProperties.hollowCandleStyle.downColor': downColor,
        'mainSeriesProperties.haStyle.upColor': upColor,
        'mainSeriesProperties.haStyle.downColor': downColor,
        'mainSeriesProperties.barStyle.upColor': upColor,
        'mainSeriesProperties.barStyle.downColor': downColor,

        'mainSeriesProperties.areaStyle.color1': upColor,
        'mainSeriesProperties.areaStyle.color2': downColor,
      },
    });
  }

  removeChart() {
    if (this.chart && 'remove' in this.chart) {
      this.chart.remove();
      this.chart = false;
    }
  }

  render() {
    const chartId = this.getId();
    return (
      <div className="SecurityContent SecurityContentChart">
        <div className="SecurityContentChart-container" id={chartId}></div>
      </div>
    );
  }
}

SecurityContentChart.propTypes = {
  symbol: React.PropTypes.string.isRequired,
  exchange: React.PropTypes.string,
  id: React.PropTypes.any
};

export default SecurityContentChart;
