'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = 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 _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec,
    _class,
    _class2,
    _temp2,
    _default_en_number = Intl.NumberFormat('en', { style: 'decimal' }).format,
    _percent_en_number = Intl.NumberFormat('en', { 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 _Distribution = require('../Distribution');

var _Distribution2 = _interopRequireDefault(_Distribution);

var _formatMessage = require('@instructure/quiz-common/lib/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__barStar {\n  fill: ' + theme.barStarFillColor + ';\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',
  'barStar': 'Distribution__styles__barStar',
  '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__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';
  },
  'centileRoot': 'CentileDistribution__styles__centileRoot',
  'barLabel': 'CentileDistribution__styles__barLabel',
  'xAxis': 'CentileDistribution__styles__xAxis'
};


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

  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 = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(CentileDistribution, _Component);

  function CentileDistribution() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, CentileDistribution);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = CentileDistribution.__proto__ || Object.getPrototypeOf(CentileDistribution)).call.apply(_ref, [this].concat(args))), _this), _this._calculateAxis = function (x, y, xAxis, height) {
      x.domain((0, _d3Array.range)(101));

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

      xAxis.tickValues((0, _d3Array.range)(0, 101, 10)).tickFormat(function (d) {
        return _default_en_number(d) + '%';
      });
    }, _this._createChart = function (svg, width) {
      // Manually redraw x axis to extend beyond container
      var axisPadding = 2000;
      svg.select('g.' + distributionStyles.xAxis + ' path').attr('d', 'M' + -1 * axisPadding + ',0H' + (width + axisPadding));

      return svg;
    }, _this._summarizeChart = function (summary) {
      if (typeof _this.props.starScore !== 'number') return summary;
      return 'You scored ' + _percent_en_number(_this.props.starScore) + '. ' + summary;
    }, _this._renderTable = function () {
      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()
          )
        )
      );
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(CentileDistribution, [{
    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() {
      var props = Object.assign({}, this.props, {
        calculateAxis: this._calculateAxis,
        createChart: this._createChart,
        renderTable: this._renderTable,
        summarizeChart: this._summarizeChart,
        starIndex: starBin(this.props)
      });

      return _react2.default.createElement(
        'div',
        { className: styles.centileRoot },
        _react2.default.createElement(_Distribution2.default, props)
      );
    }
  }]);
  CentileDistribution.displayName = 'CentileDistribution'
  ;
  return CentileDistribution;
}(_react.Component), _class2.propTypes = {
  animateDelay: _propTypes.PropTypes.number,
  animateDuration: _propTypes.PropTypes.number,
  barPaddingInner: _propTypes.PropTypes.number, // Spacing between bars, so each is visible, could be accomplished by borders
  barPaddingOuter: _propTypes.PropTypes.number, // Spacing between bars, so each is visible, could be accomplished by borders
  barPaddingTop: _propTypes.PropTypes.number,
  chartHeight: _propTypes.PropTypes.number.isRequired, // Height in pixels
  chartWidth: _propTypes.PropTypes.number,
  /* *
   * * a fallback minimal distribution for tab-able, keyboard navigable buckets
   * * typically this will be ~ 10 buckets
   * */
  summaryDistribution: _propTypes.PropTypes.arrayOf(_propTypes.PropTypes.node),
  /* *
   * * A list of score values for each bucket.  Size of this array determines the number of buckets
   * */
  visualDistribution: _propTypes.PropTypes.arrayOf(_propTypes.PropTypes.node).isRequired,
  starScore: _propTypes.PropTypes.number
}, _class2.defaultProps = {
  animateDelay: 200,
  animateDuration: 900,
  barPaddingInner: 0.25, // Spacing between bars, so each is visible, could be accomplished by borders
  barPaddingOuter: 0, // Spacing between bars, so each is visible, could be accomplished by borders
  barPaddingTop: 0, // Spacing between highest bar and top of chart, pixels
  chartHeight: 200, // Height in pixels
  chartWidth: 900,
  visualDistribution: [],
  starScore: null
}, _temp2)) || _class);
exports.default = CentileDistribution;