'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.starPathData = undefined;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = require('babel-runtime/helpers/get');

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec,
    _class,
    _class2,
    _temp,
    _default_nb_k12_number = Intl.NumberFormat('nb_k12', { style: 'decimal' }).format,
    _percent_nb_k12_number = Intl.NumberFormat('nb_k12', { style: 'percent' }).format; /* eslint "import/no-extraneous-dependencies": "warn" */


// TODO change the d3 dependency in package.json to match specific modules


var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _d3Array = require('d3-array');

var _lib = require('@instructure/ui-themeable/lib');

var _lib2 = _interopRequireDefault(_lib);

var _ScreenReaderContent = require('@instructure/ui-a11y/lib/components/ScreenReaderContent');

var _ScreenReaderContent2 = _interopRequireDefault(_ScreenReaderContent);

var _Table = require('@instructure/ui-elements/lib/components/Table');

var _Table2 = _interopRequireDefault(_Table);

var _Distribution2 = require('../Distribution');

var _Distribution3 = _interopRequireDefault(_Distribution2);

var _formatMessage = require('../../../../common/format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

var _theme = require('./theme');

var _theme2 = _interopRequireDefault(_theme);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var distributionStyles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n.Distribution__styles__bar {\n  fill: ' + theme.barFillColor + ';\n}\n\n.Distribution__styles__barContainer {\n}\n\n.Distribution__styles__xAxis {\n}\n\n.Distribution__styles__barLabel {\n  font-family: ' + theme.barLabelFontFamily + ';\n  font-size: ' + theme.barLabelFontSize + ';\n  text-anchor: middle;\n}\n';
  },
  'bar': 'Distribution__styles__bar',
  'barContainer': 'Distribution__styles__barContainer',
  'xAxis': 'Distribution__styles__xAxis',
  'barLabel': 'Distribution__styles__barLabel'
};
var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n.CentileDistribution__styles__bar {\n  fill: ' + theme.barFillColor + ';\n}\n\n.CentileDistribution__styles__barStar {\n  fill: ' + theme.barStarFillColor + ';\n}\n\n.CentileDistribution__styles__centileRoot {\n  display: flex;\n  flex-direction: row;\n  justify-content: center;\n  overflow: hidden;\n}\n\n.CentileDistribution__styles__centileRoot > div {\n    flex: 0 1 51rem;\n  }\n\n.CentileDistribution__styles__centileRoot svg {\n  overflow: visible;\n}\n\n@media screen and (--phoneBreakPoint) {\n    .CentileDistribution__styles__centileRoot .CentileDistribution__styles__barLabel {\n      font-size: ' + theme.phoneBarLabelFontSize + ';\n    }\n\n    .CentileDistribution__styles__centileRoot .CentileDistribution__styles__xAxis g:nth-child(2n+1) {\n      display: none;\n    }\n}\n';
  },
  'bar': 'CentileDistribution__styles__bar',
  'barStar': 'CentileDistribution__styles__barStar',
  'centileRoot': 'CentileDistribution__styles__centileRoot',
  'barLabel': 'CentileDistribution__styles__barLabel',
  'xAxis': 'CentileDistribution__styles__xAxis'
};


// Star path copied from instructure-icons/svg/Solid/star.svg
// eslint-disable-next-line max-len
var starPathData = exports.starPathData = 'M1915.918 737.475c-10.955-33.543-42.014-56.131-77.364-56.131h-612.029l-189.063-582.1v-.112C1026.394 65.588 995.335 43 959.984 43c-35.237 0-66.41 22.588-77.365 56.245L693.443 681.344H81.415c-35.35 0-66.41 22.588-77.365 56.131-10.955 33.544.79 70.137 29.478 91.03l495.247 359.831-189.177 582.212c-10.955 33.657 1.13 70.25 29.817 90.918 14.23 10.278 30.946 15.473 47.66 15.473 16.716 0 33.432-5.195 47.775-15.586l495.134-359.718 495.021 359.718c28.574 20.781 67.087 20.781 95.662.113 28.687-20.668 40.658-57.261 29.703-91.03l-189.176-582.1 495.36-359.83c28.574-20.894 40.433-57.487 29.364-91.03';

var starBin = function starBin(props) {
  if (typeof props.starScore !== 'number') return -1;

  var starScore = Math.max(0, Math.min(props.starScore, 1));
  // min+floor here matches quiz_etl HistogramHelper
  return Math.min(Math.floor(starScore * props.visualDistribution.length), props.visualDistribution.length - 1);
};

var CentileDistribution = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp = _class2 = function (_Distribution) {
  (0, _inherits3.default)(CentileDistribution, _Distribution);

  function CentileDistribution() {
    (0, _classCallCheck3.default)(this, CentileDistribution);
    return (0, _possibleConstructorReturn3.default)(this, (CentileDistribution.__proto__ || Object.getPrototypeOf(CentileDistribution)).apply(this, arguments));
  }

  (0, _createClass3.default)(CentileDistribution, [{
    key: 'calculateAxis',
    value: function calculateAxis(props) {
      (0, _get3.default)(CentileDistribution.prototype.__proto__ || Object.getPrototypeOf(CentileDistribution.prototype), 'calculateAxis', this).call(this, props);

      this.x = this.x.domain((0, _d3Array.range)(101));

      if (typeof props.starScore === 'number') {
        var starIndex = starBin(props);
        // Determine if star above bar will overflow height, and reduce range to
        // account for 18 star height + 12 star bottom padding
        var starTop = this.y(props.visualDistribution[starIndex]) - 30;
        this.y.rangeRound([this.height, props.barPaddingTop - Math.min(0, starTop)]);
      }

      this.xAxis = this.xAxis.tickValues((0, _d3Array.range)(0, 101, 10)).tickFormat(function (d) {
        return _default_nb_k12_number(d) + '%';
      });
    }
  }, {
    key: 'createChart',
    value: function createChart(node, props) {
      var svg = (0, _get3.default)(CentileDistribution.prototype.__proto__ || Object.getPrototypeOf(CentileDistribution.prototype), 'createChart', this).call(this, node, Object.assign({}, props, { chartWidth: 900 }));

      // Manually redraw x axis to extend beyond container
      var axisPadding = 2000;
      svg.select('g.' + distributionStyles.xAxis + ' path').attr('d', 'M' + -1 * axisPadding + ',0H' + (this.width + axisPadding));

      return svg;
    }
  }, {
    key: 'renderBars',
    value: function renderBars(node, props, _) {
      (0, _get3.default)(CentileDistribution.prototype.__proto__ || Object.getPrototypeOf(CentileDistribution.prototype), 'renderBars', this).call(this, node, props, styles.bar);

      if (typeof props.starScore !== 'number') return;

      var starIndex = starBin(props);
      var starBar = node.selectAll('rect').filter(function (d, i) {
        return i === starIndex;
      });
      starBar.classed(styles.barStar, true);
    }
  }, {
    key: 'summarizeChart',
    value: function summarizeChart() {
      var summary = (0, _get3.default)(CentileDistribution.prototype.__proto__ || Object.getPrototypeOf(CentileDistribution.prototype), 'summarizeChart', this).call(this);
      if (typeof this.props.starScore !== 'number') return summary;
      return 'You scored ' + _percent_nb_k12_number(this.props.starScore) + '. ' + summary;
    }
  }, {
    key: 'updateChart',
    value: function updateChart(svg, props) {
      (0, _get3.default)(CentileDistribution.prototype.__proto__ || Object.getPrototypeOf(CentileDistribution.prototype), 'updateChart', this).call(this, svg, props);
      this.renderStar(svg, props);
    }
  }, {
    key: 'renderStar',
    value: function renderStar(node, props) {
      if (typeof props.starScore !== 'number') return;

      var star = node.append('path').attr('d', starPathData).classed(styles.barStar, true);

      var starIndex = starBin(props);
      var starX = this.x(starIndex) + this.x.bandwidth() / 2;
      var starY = this.y(props.visualDistribution[starIndex]) - 30;
      // scale the star down and position it on the x axis - y axis will be applied by animation
      var xTransform = 'translate(' + starX + ' 0) scale(0.011) translate(-960 0)';
      this.applyTransition(star, function (rects) {
        return rects.attr('opacity', 0).attr('transform', 'translate(0 ' + (starY + 20) + ') ' + xTransform);
      }, function (rects) {
        return rects.attr('opacity', 1).attr('transform', 'translate(0 ' + starY + ') ' + xTransform);
      }, function (transition) {
        return transition.delay(props.animateDuration).duration(600);
      });
    }
  }, {
    key: 'renderTable',
    value: function renderTable() {
      return _react2.default.createElement(
        _ScreenReaderContent2.default,
        null,
        _react2.default.createElement(
          _Table2.default,
          { caption: 'Score percentiles chart data' },
          _react2.default.createElement(
            'thead',
            null,
            _react2.default.createElement(
              'tr',
              null,
              _react2.default.createElement(
                'th',
                { scope: 'col' },
                'Score Percentile'
              ),
              _react2.default.createElement(
                'th',
                { scope: 'col' },
                'Count'
              )
            )
          ),
          _react2.default.createElement(
            'tbody',
            null,
            this.renderTableRows()
          )
        )
      );
    }
  }, {
    key: 'renderTableRows',
    value: function renderTableRows() {
      var chartData = this.props.visualDistribution;

      return chartData.map(function (count, index) {
        return _react2.default.createElement(
          'tr',
          { key: index + ':' + count },
          _react2.default.createElement(
            'td',
            null,
            index + '%'
          ),
          _react2.default.createElement(
            'td',
            null,
            count
          )
        );
      });
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        { className: styles.centileRoot },
        (0, _get3.default)(CentileDistribution.prototype.__proto__ || Object.getPrototypeOf(CentileDistribution.prototype), 'render', this).call(this)
      );
    }
  }]);
  CentileDistribution.displayName = 'CentileDistribution'
  ;
  return CentileDistribution;
}(_Distribution3.default), _class2.propTypes = Object.assign({}, _Distribution3.default.propTypes, {
  starScore: _propTypes.PropTypes.number
}), _class2.defaultProps = Object.assign({}, _Distribution3.default.defaultProps, {
  starScore: null
}), _temp)) || _class);
exports.default = CentileDistribution;