"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.RawPlot = exports.Plot = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _Check = _interopRequireDefault(require("@material-ui/icons/Check"));

var _index = require("@material-ui/core/styles/index");

var _group = require("@vx/group");

var _debug = _interopRequireDefault(require("debug"));

var _plot = require("../../../plot");

var _dragHandle = _interopRequireWildcard(require("../../common/drag-handle"));

var _renderUi = require("../../../render-ui");

var _utils = require("../../utils");

var _styles = require("../../common/styles");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var log = (0, _debug["default"])('pie-lib:chart:bars');
var ICON_SIZE = 24;

var RawPlot = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(RawPlot, _React$Component);

  var _super = _createSuper(RawPlot);

  function RawPlot(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, RawPlot);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleMouseEnter", function () {
      _this.setState({
        isHovered: true
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleMouseLeave", function () {
      _this.setState({
        isHovered: false
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setDragValue", function (dragValue) {
      return _this.setState({
        dragValue: dragValue
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "dragStop", function () {
      var _this$props = _this.props,
          label = _this$props.label,
          onChangeCategory = _this$props.onChangeCategory;
      var dragValue = _this.state.dragValue;
      log('[dragStop]', dragValue);

      if (dragValue !== undefined) {
        onChangeCategory({
          label: label,
          value: dragValue
        });
      }

      _this.setDragValue(undefined);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "dragValue", function (existing, next) {
      log('[dragValue] next:', next);

      _this.setDragValue(next);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "renderCorrectnessIcon", function (barX, barWidth, correctVal, correctness, classes, scale) {
      return /*#__PURE__*/_react["default"].createElement("foreignObject", {
        x: barX + barWidth / 2 - ICON_SIZE / 2 + 1 // 1 px for the border
        ,
        y: scale.y(correctVal) + ICON_SIZE / 2 + 1,
        width: ICON_SIZE,
        height: ICON_SIZE
      }, /*#__PURE__*/_react["default"].createElement(_Check["default"], {
        className: (0, _classnames["default"])(classes.correctnessIcon, classes.correctIcon),
        title: correctness.label
      }));
    });
    _this.state = {
      dragValue: undefined,
      isHovered: false
    };
    return _this;
  }

  (0, _createClass2["default"])(RawPlot, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props2 = this.props,
          graphProps = _this$props2.graphProps,
          value = _this$props2.value,
          label = _this$props2.label,
          classes = _this$props2.classes,
          xBand = _this$props2.xBand,
          index = _this$props2.index,
          CustomBarElement = _this$props2.CustomBarElement,
          interactive = _this$props2.interactive,
          correctness = _this$props2.correctness,
          defineChart = _this$props2.defineChart,
          correctData = _this$props2.correctData;
      var scale = graphProps.scale,
          range = graphProps.range,
          size = graphProps.size;

      var _ref = range || {},
          max = _ref.max;

      var _this$state = this.state,
          dragValue = _this$state.dragValue,
          isHovered = _this$state.isHovered;
      var v = Number.isFinite(dragValue) ? dragValue : value;
      var barWidth = xBand.bandwidth();
      var barHeight = scale.y(range.max - v);
      var barX = xBand((0, _utils.bandKey)({
        label: label
      }, index));
      log('label:', label, 'barX:', barX, 'v: ', v, 'barHeight:', barHeight, 'barWidth: ', barWidth);
      var values = [];

      for (var i = 0; i < v; i++) {
        values.push(i);
      }

      var pointHeight = size.height / max;
      var pointDiameter = (pointHeight > barWidth ? barWidth : pointHeight) * 0.8;
      var Component = interactive ? _dragHandle["default"] : _dragHandle.DragHandle;
      var allowRolloverEvent = interactive && !correctness;
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("g", {
        onMouseEnter: this.handleMouseEnter,
        onMouseLeave: this.handleMouseLeave,
        onTouchStart: this.handleMouseEnter,
        onTouchEnd: this.handleMouseLeave
      }, isHovered && allowRolloverEvent && /*#__PURE__*/_react["default"].createElement("rect", {
        x: barX,
        y: scale.y(v),
        width: barWidth,
        height: values !== null && values !== void 0 && values.length ? pointHeight * values.length : 0,
        stroke: _renderUi.color.defaults.BORDER_GRAY,
        strokeWidth: '4px',
        fill: 'transparent'
      }), values.map(function (index) {
        return CustomBarElement({
          index: index,
          pointDiameter: pointDiameter,
          barX: barX,
          barWidth: barWidth,
          pointHeight: pointHeight,
          label: label,
          value: value,
          classes: classes,
          scale: scale
        });
      }), correctness && correctness.value === 'incorrect' && function () {
        var correctVal = parseFloat(correctData[index] && correctData[index].value);
        if (isNaN(correctVal)) return null;
        var selectedVal = v;

        if (selectedVal > correctVal) {
          // selected is higher than correct: overlay the correct last segment
          var overlayValues = [];

          for (var _i = 0; _i < correctVal; _i++) {
            overlayValues.push(_i);
          }

          var lastIndexOfOverlay = overlayValues.length - 1;
          var lastOverlayValue = overlayValues[lastIndexOfOverlay];

          var _barX = xBand((0, _utils.bandKey)({
            label: label
          }, index));

          var _barWidth = xBand.bandwidth();

          var _pointHeight = size.height / max;

          var _pointDiameter = (_pointHeight > _barWidth ? _barWidth : _pointHeight) * 0.8;

          return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(CustomBarElement, {
            index: lastOverlayValue,
            pointDiameter: _pointDiameter + 10 // increase point diameter for dotted line
            ,
            barX: _barX,
            barWidth: _barWidth,
            pointHeight: _pointHeight,
            label: label,
            value: value,
            classes: classes,
            scale: scale,
            dottedOverline: true
          }), _this2.renderCorrectnessIcon(_barX, _barWidth, correctVal, correctness, classes, scale));
        } // selected is lower than correct, render missing segment below the correct bar


        var valuesToRender = [];

        for (var _i2 = selectedVal; _i2 < correctVal; _i2++) {
          valuesToRender.push(_i2);
        }

        return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, valuesToRender.map(function (idx) {
          return CustomBarElement({
            index: idx,
            pointDiameter: pointDiameter,
            barX: barX,
            barWidth: barWidth,
            pointHeight: pointHeight,
            label: label,
            value: value,
            classes: classes,
            scale: scale,
            dottedOverline: true
          });
        }), _this2.renderCorrectnessIcon(barX, barWidth, correctVal, correctness, classes, scale));
      }(), /*#__PURE__*/_react["default"].createElement(Component, {
        x: barX,
        y: v,
        interactive: interactive,
        width: barWidth,
        onDrag: function onDrag(v) {
          return _this2.dragValue(value, v);
        },
        onDragStop: this.dragStop,
        graphProps: graphProps,
        correctness: correctness,
        isHovered: isHovered,
        defineChart: defineChart,
        color: _renderUi.color.primaryDark(),
        isPlot: true
      })));
    }
  }]);
  return RawPlot;
}(_react["default"].Component);

exports.RawPlot = RawPlot;
(0, _defineProperty2["default"])(RawPlot, "propTypes", {
  onChangeCategory: _propTypes["default"].func,
  value: _propTypes["default"].number,
  classes: _propTypes["default"].object,
  label: _propTypes["default"].string,
  xBand: _propTypes["default"].func,
  index: _propTypes["default"].number.isRequired,
  graphProps: _plot.types.GraphPropsType.isRequired,
  CustomBarElement: _propTypes["default"].func,
  interactive: _propTypes["default"].bool,
  correctness: _propTypes["default"].shape({
    value: _propTypes["default"].string,
    label: _propTypes["default"].string
  })
});
var Bar = (0, _index.withStyles)(function (theme) {
  return {
    dot: {
      fill: _renderUi.color.visualElementsColors.PLOT_FILL_COLOR,
      '&.correct': (0, _styles.correct)('stroke'),
      '&.incorrect': (0, _styles.incorrect)('stroke')
    },
    dotColor: {
      fill: _renderUi.color.visualElementsColors.PLOT_FILL_COLOR,
      '&.correct': (0, _styles.correct)('fill'),
      '&.incorrect': (0, _styles.incorrect)('fill')
    },
    line: {
      stroke: _renderUi.color.visualElementsColors.PLOT_FILL_COLOR,
      '&.correct': (0, _styles.correct)('stroke'),
      '&.incorrect': (0, _styles.incorrect)('stroke')
    },
    correctIcon: {
      backgroundColor: _renderUi.color.correct()
    },
    incorrectIcon: {
      backgroundColor: _renderUi.color.incorrectWithIcon()
    },
    correctnessIcon: {
      borderRadius: theme.spacing.unit * 2,
      color: _renderUi.color.defaults.WHITE,
      fontSize: '16px',
      padding: '2px',
      border: "1px solid ".concat(_renderUi.color.defaults.WHITE),
      stroke: 'initial'
    }
  };
})(RawPlot);

var Plot = /*#__PURE__*/function (_React$Component2) {
  (0, _inherits2["default"])(Plot, _React$Component2);

  var _super2 = _createSuper(Plot);

  function Plot() {
    (0, _classCallCheck2["default"])(this, Plot);
    return _super2.apply(this, arguments);
  }

  (0, _createClass2["default"])(Plot, [{
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          data = _this$props3.data,
          graphProps = _this$props3.graphProps,
          xBand = _this$props3.xBand,
          CustomBarElement = _this$props3.CustomBarElement,
          _onChangeCategory = _this$props3.onChangeCategory,
          defineChart = _this$props3.defineChart,
          correctData = _this$props3.correctData;
      return /*#__PURE__*/_react["default"].createElement(_group.Group, null, (data || []).map(function (d, index) {
        return /*#__PURE__*/_react["default"].createElement(Bar, {
          value: d.value,
          label: d.label,
          interactive: defineChart || d.interactive,
          defineChart: defineChart,
          xBand: xBand,
          index: index,
          key: "bar-".concat(d.label, "-").concat(d.value, "-").concat(index),
          onChangeCategory: function onChangeCategory(category) {
            return _onChangeCategory(index, category);
          },
          graphProps: graphProps,
          CustomBarElement: CustomBarElement,
          correctness: d.correctness,
          correctData: correctData
        });
      }));
    }
  }]);
  return Plot;
}(_react["default"].Component);

exports.Plot = Plot;
(0, _defineProperty2["default"])(Plot, "propTypes", {
  data: _propTypes["default"].array,
  onChangeCategory: _propTypes["default"].func,
  xBand: _propTypes["default"].func,
  graphProps: _plot.types.GraphPropsType.isRequired,
  defineChart: _propTypes["default"].bool,
  CustomBarElement: _propTypes["default"].func
});
var _default = Plot;
exports["default"] = _default;
//# sourceMappingURL=plot.js.map