import React from 'react';
import { connect } from 'react-redux';
import { quoteService } from 'services';
import connectService from 'services/connect';
import classnames from 'classnames';
import Immutable from 'immutable';
import { openSecurity } from 'actions/workspaces';
import { numberPercent } from 'utils/formatters';

class Ticker extends React.Component {
  constructor(props) {
    super(props);
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (this.props.symbol !== nextProps.symbol || this.props.companyName !== nextProps.companyName
            || this.props.price !== nextProps.price || this.props.initialPrice !== nextProps.initialPrice);
  }

  render() {
    // Neutral by default;
    let directionDay = null;
    let directionStory = null;

    if (this.props.percentChange > 0) {
      directionDay = 'up';
    } else if (this.props.percentChange < 0) {
      directionDay = 'down';
    }

    let storyPercent = 0;
    let storyNominal = 0;
    if (this.props.publishQuote && this.props.publishQuote.Price !== '') {
      storyNominal = (this.props.price - this.props.publishQuote.Price).toFixed(2);
      storyPercent = (storyNominal / this.props.publishQuote.Price);
    }

    if (storyNominal > 0) {
      directionStory = 'up';
    } else if (storyNominal < 0) {
      directionStory = 'down';
    }

    const dayClass = classnames({'u-upText': directionDay === 'up', 'u-downText': directionDay === 'down'});
    const storyClass = classnames({'u-upText': directionStory === 'up', 'u-downText': directionStory === 'down'});

    return (
      <span className="FeedStory-symbols__ticker" onClick={() => openSecurity(this.props.symbol)}>
        <span className={dayClass}>{this.props.symbol}</span>
        <article className="TickerTooltip">
          <div className="TickerTooltip-price">{this.props.price}</div>
          <div className="TickerTooltip-security">({this.props.symbol}) {this.props.companyName}</div>
          <div className="TickerTooltip-changes">
            <article>
              <h1 className={dayClass}>{this.props.nominalChange }  ({numberPercent(this.props.percentChange ? this.props.percentChange : 0.0, false)})</h1>
              <h2>Change Today</h2>
            </article>
            <article>
              <h1 className={storyClass}>{storyNominal}  ({numberPercent(storyPercent)})</h1>
              <h2 className={storyClass}>Change Since Publish</h2>
            </article>
          </div>
        </article>
      </span>
    );
  }
}

Ticker.propTypes = {
  service: React.PropTypes.object,
  symbol: React.PropTypes.string,
  companyName: React.PropTypes.string,
  price: React.PropTypes.number,
  percentChange: React.PropTypes.number,
  nominalChange: React.PropTypes.number,
  initialPrice: React.PropTypes.string,
  publishQuote: React.PropTypes.object,
};

export default connectService(quoteService)(Ticker);
