'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactVis = require('react-vis');

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _empty_prompt = require('../empty_prompt');

var _selection_brush = require('./selection_brush');

var _default_axis = require('./axis/default_axis');

var _crosshair_x = require('./crosshairs/crosshair_x');

var _crosshair_y = require('./crosshairs/crosshair_y');

var _services = require('../../services');

var _chart_utils = require('./utils/chart_utils');

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var HORIZONTAL = _chart_utils.ORIENTATION.HORIZONTAL,
    VERTICAL = _chart_utils.ORIENTATION.VERTICAL,
    BOTH = _chart_utils.ORIENTATION.BOTH;
var LINEAR = _chart_utils.SCALE.LINEAR,
    ORDINAL = _chart_utils.SCALE.ORDINAL,
    CATEGORY = _chart_utils.SCALE.CATEGORY,
    TIME = _chart_utils.SCALE.TIME,
    TIME_UTC = _chart_utils.SCALE.TIME_UTC,
    LOG = _chart_utils.SCALE.LOG,
    LITERAL = _chart_utils.SCALE.LITERAL;


var DEFAULT_MARGINS = {
  left: 40,
  right: 10,
  top: 10,
  bottom: 40
};

/**
 * The root component of any XY chart.
 * It renders an react-vis XYPlot including default axis and a valid crosshair.
 * You can also enable the Selection Brush.
 */

var XYChart = function (_PureComponent) {
  _inherits(XYChart, _PureComponent);

  function XYChart() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, XYChart);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = XYChart.__proto__ || Object.getPrototypeOf(XYChart)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      mouseOver: false
    }, _this.colorIterator = 0, _this._xyPlotRef = _react2.default.createRef(), _this._getSeriesNames = function (children) {
      return _react2.default.Children.toArray(children).filter(_this._isAbstractSeries).map(function (_ref2) {
        var name = _ref2.props.name;
        return name;
      });
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(XYChart, [{
    key: '_isEmptyPlot',


    /**
     * Checks if the plot is empty, looking at existing series and data props.
     */
    value: function _isEmptyPlot(children) {
      return _react2.default.Children.toArray(children).filter(this._isAbstractSeries).filter(function (child) {
        return child.props.data && child.props.data.length > 0;
      }).length === 0;
    }

    /**
     * Checks if a react child is an AbstractSeries
     */

  }, {
    key: '_isAbstractSeries',
    value: function _isAbstractSeries(child) {
      var prototype = child.type.prototype;
      // Avoid applying chart props to non series children

      return prototype instanceof _reactVis.AbstractSeries;
    }

    /**
     * Render children adding a valid EUI visualization color if the color prop is not specified.
     */

  }, {
    key: '_renderChildren',
    value: function _renderChildren(children) {
      var _this2 = this;

      var colorIterator = 0;

      return _react2.default.Children.map(children, function (child, i) {
        // Avoid applying color props to non series children
        if (!_this2._isAbstractSeries(child)) {
          return child;
        }

        var props = {
          id: 'chart-' + i
        };
        if (!child.props.color) {
          props.color = _services.VISUALIZATION_COLORS[colorIterator % _services.VISUALIZATION_COLORS.length];
          colorIterator++;
        }
        props._orientation = _this2.props.orientation;

        return _react2.default.cloneElement(child, props);
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          children = _props.children,
          width = _props.width,
          height = _props.height,
          xType = _props.xType,
          yType = _props.yType,
          stackBy = _props.stackBy,
          statusText = _props.statusText,
          xDomain = _props.xDomain,
          yDomain = _props.yDomain,
          yPadding = _props.yPadding,
          xPadding = _props.xPadding,
          animateData = _props.animateData,
          showDefaultAxis = _props.showDefaultAxis,
          showCrosshair = _props.showCrosshair,
          enableSelectionBrush = _props.enableSelectionBrush,
          selectionBrushOrientation = _props.selectionBrushOrientation,
          onSelectionBrushEnd = _props.onSelectionBrushEnd,
          orientation = _props.orientation,
          crosshairValue = _props.crosshairValue,
          onCrosshairUpdate = _props.onCrosshairUpdate,
          rest = _objectWithoutProperties(_props, ['children', 'width', 'height', 'xType', 'yType', 'stackBy', 'statusText', 'xDomain', 'yDomain', 'yPadding', 'xPadding', 'animateData', 'showDefaultAxis', 'showCrosshair', 'enableSelectionBrush', 'selectionBrushOrientation', 'onSelectionBrushEnd', 'orientation', 'crosshairValue', 'onCrosshairUpdate']);

      if (this._isEmptyPlot(children)) {
        return _react2.default.createElement(_empty_prompt.EuiEmptyPrompt, {
          iconType: 'stats',
          title: _react2.default.createElement(
            'h2',
            null,
            'Chart not available'
          ),
          body: _react2.default.createElement(
            _react.Fragment,
            null,
            _react2.default.createElement(
              'p',
              null,
              statusText
            )
          )
        });
      }

      var Crosshair = orientation === HORIZONTAL ? _crosshair_y.EuiCrosshairY : _crosshair_x.EuiCrosshairX;
      var seriesNames = this._getSeriesNames(children);
      return _react2.default.createElement(
        'div',
        rest,
        _react2.default.createElement(
          _reactVis.XYPlot,
          {
            ref: this._xyPlotRef,
            dontCheckIfEmpty: true,
            width: width,
            animation: animateData,
            height: height,
            margin: DEFAULT_MARGINS,
            xType: xType,
            yType: yType,
            xDomain: xDomain,
            yDomain: yDomain,
            stackBy: stackBy,
            yPadding: yPadding,
            xPadding: xPadding
          },
          this._renderChildren(children),
          showDefaultAxis && _react2.default.createElement(_default_axis.EuiDefaultAxis, { orientation: orientation }),
          showCrosshair && _react2.default.createElement(Crosshair, { seriesNames: seriesNames, crosshairValue: crosshairValue, onCrosshairUpdate: onCrosshairUpdate }),
          enableSelectionBrush && _react2.default.createElement(_selection_brush.EuiSelectionBrush, {
            onBrushEnd: onSelectionBrushEnd,
            orientation: selectionBrushOrientation
          })
        )
      );
    }
  }]);

  return XYChart;
}(_react.PureComponent);

XYChart.displayName = 'EuiXYChart';

XYChart.propTypes = {
  /** The initial width of the chart. */
  width: _propTypes2.default.number.isRequired,
  /** The initial height of the chart. */
  height: _propTypes2.default.number.isRequired,
  /** **experimental** The orientation of the chart. */
  orientation: _propTypes2.default.oneOf([HORIZONTAL, VERTICAL]),
  /** If the chart animates on data changes. */
  animateData: _propTypes2.default.bool,
  /** TODO */
  stackBy: _propTypes2.default.string,
  /** The main x axis scale type. See https://github.com/uber/react-vis/blob/master/docs/scales-and-data.md */
  xType: _propTypes2.default.oneOf([LINEAR, ORDINAL, CATEGORY, TIME, TIME_UTC, LOG, LITERAL]),
  /** The main y axis scale type. See https://github.com/uber/react-vis/blob/master/docs/scales-and-data.md*/
  yType: _propTypes2.default.oneOf([LINEAR, ORDINAL, CATEGORY, TIME, TIME_UTC, LOG, LITERAL]),
  /** Manually specify the domain of x axis. */
  xDomain: _propTypes2.default.array,
  /** Manually specify the domain of y axis. */
  yDomain: _propTypes2.default.array,
  /** The horizontal padding between the chart borders and chart elements. */
  xPadding: _propTypes2.default.number,
  /** The vertical padding between the chart borders and chart elements. */
  yPadding: _propTypes2.default.number,
  /** Add an additional status text above the graph status message*/
  statusText: _propTypes2.default.string,
  /** Shows the crosshair tooltip on mouse move.*/
  showCrosshair: _propTypes2.default.bool,
  /** Specify the axis value where to display crosshair based on chart orientation value. */
  crosshairValue: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  /** Callback when the crosshair position is updated. */
  onCrosshairUpdate: _propTypes2.default.func,
  /** Show the default X and Y axis. */
  showDefaultAxis: _propTypes2.default.bool,
  /** Enable the brush tool */
  enableSelectionBrush: _propTypes2.default.bool,
  /** Specify the brush orientation */
  selectionBrushOrientation: _propTypes2.default.oneOf([HORIZONTAL, VERTICAL, BOTH]),
  /** Callback on brush end event with { begin, end } object returned. */
  onSelectionBrushEnd: _propTypes2.default.func
};

XYChart.defaultProps = {
  animateData: true,
  xType: 'linear',
  yType: 'linear',
  yPadding: 0,
  xPadding: 0,
  orientation: VERTICAL,
  showCrosshair: true,
  showDefaultAxis: true,
  enableSelectionBrush: false,
  selectionBrushOrientation: HORIZONTAL
};

var EuiXYChart = exports.EuiXYChart = (0, _reactVis.makeVisFlexible)(XYChart);