"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.swap = exports["default"] = exports.buildLines = exports.RawBaseComponent = exports.BaseComponent = void 0;

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

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 _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

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

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

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

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

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

var _types = require("../shared/types");

var _chunk = _interopRequireDefault(require("lodash/chunk"));

var _initial = _interopRequireDefault(require("lodash/initial"));

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

var _polygon = _interopRequireDefault(require("./polygon"));

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

var _invariant = _interopRequireDefault(require("invariant"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _markLabel = _interopRequireDefault(require("../../mark-label"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

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

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; } }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

var log = (0, _debug["default"])('pie-lib:graphing-solution-set:polygon');

var buildLines = function buildLines(points, closed) {
  var expanded = points.reduce(function (acc, p, index) {
    acc.push(_objectSpread(_objectSpread({}, p), {}, {
      index: index
    }));
    var isLast = index === points.length - 1;
    var next = isLast ? 0 : index + 1;
    acc.push(_objectSpread(_objectSpread({}, points[next]), {}, {
      index: next
    }));
    return acc;
  }, []);
  var all = (0, _chunk["default"])(expanded, 2).map(function (_ref) {
    var _ref2 = (0, _slicedToArray2["default"])(_ref, 2),
        from = _ref2[0],
        to = _ref2[1];

    return {
      from: from,
      to: to
    };
  });
  return closed ? all : (0, _initial["default"])(all);
};

exports.buildLines = buildLines;

var swap = function swap(arr) {
  for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    rest[_key - 1] = arguments[_key];
  }

  var pairs = (0, _chunk["default"])(rest, 2);
  return pairs.reduce(function (acc, pr) {
    if (pr.length === 2) {
      var _pr = (0, _slicedToArray2["default"])(pr, 2),
          e = _pr[0],
          replacement = _pr[1];

      (0, _invariant["default"])(Number.isFinite(e.index), 'Index must be defined');
      var index = e.index; // const i = acc.findIndex(pt => pt.x === e.x && pt.y === e.y);

      if (index >= 0) {
        acc.splice(index, 1, replacement);
        return acc;
      } else {
        return acc;
      }
    } else {
      return acc;
    }
  }, (0, _toConsumableArray2["default"])(arr));
};

exports.swap = swap;

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

  var _super = _createSuper(RawBaseComponent);

  function RawBaseComponent() {
    var _this;

    (0, _classCallCheck2["default"])(this, RawBaseComponent);

    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "dragPoint", function (index, from, to) {
      log('[dragPoint] from, to:', from, to);
      var _this$props = _this.props,
          onChange = _this$props.onChange,
          points = _this$props.points;
      var update = (0, _toConsumableArray2["default"])(points);
      var overlapPoint = !!(points || []).find(function (p) {
        return (0, _utils.equalPoints)(p, to);
      });

      if ((0, _utils.equalPoints)(from, to) || overlapPoint) {
        return;
      }

      if (points[index].label) {
        to.label = points[index].label;
      }

      update.splice(index, 1, to);
      onChange(update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "dragLine", function (existing, next) {
      log('[dragLine]: ', existing, next);
      var onChange = _this.props.onChange;

      if (existing.from.label) {
        next.from.label = existing.from.label;
      }

      if (existing.to.label) {
        next.to.label = existing.to.label;
      }

      var points = swap(_this.props.points, existing.from, next.from, existing.to, next.to);
      onChange(points);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "dragPoly", function (existing, next) {
      log('[dragPoly] ', existing, next);
      var onChange = _this.props.onChange;
      next.forEach(function (point, index) {
        if (existing[index].label) {
          next[index].label = existing[index].label;
        }
      });
      onChange(next);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "close", function () {
      var _this$props2 = _this.props,
          points = _this$props2.points,
          onClosePolygon = _this$props2.onClosePolygon;
      log('[close] ...');

      if (points.length >= 3) {
        onClosePolygon();
      } else {
        log('[close] - nope');
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "labelChange", function (point, index) {
      var _this$props3 = _this.props,
          points = _this$props3.points,
          onChangeProps = _this$props3.onChangeProps;

      var updatedPoint = _objectSpread({}, point);

      if (!point.label || (0, _isEmpty["default"])(point.label)) {
        delete updatedPoint.label;
      }

      var update = (0, _toConsumableArray2["default"])(points);
      update.splice(index, 1, updatedPoint);
      onChangeProps(update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "clickPoint", function (point, index, data) {
      var _this$props4 = _this.props,
          closed = _this$props4.closed,
          disabled = _this$props4.disabled,
          onClick = _this$props4.onClick,
          isToolActive = _this$props4.isToolActive,
          labelModeEnabled = _this$props4.labelModeEnabled,
          onChangeProps = _this$props4.onChangeProps,
          onChangeLabelProps = _this$props4.onChangeLabelProps,
          points = _this$props4.points;

      if (labelModeEnabled) {
        if (disabled) {
          return;
        }

        if (points && index === points.length) {
          var _getRightestPoints = (0, _utils.getRightestPoints)(points),
              a = _getRightestPoints.a,
              b = _getRightestPoints.b;

          var middle = _objectSpread(_objectSpread({
            label: ''
          }, point), (0, _utils.getMiddleOfTwoPoints)(a, b));

          onChangeLabelProps(middle);
        } else {
          var update = (0, _toConsumableArray2["default"])(points);
          update.splice(index, 1, _objectSpread({
            label: ''
          }, point));
          onChangeProps(update);
        }

        if (_this.input[index]) {
          _this.input[index].focus();
        }

        return;
      }

      if (isToolActive && !closed && index === 0) {
        _this.close();

        return;
      }

      onClick(point || data);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "input", {});
    return _this;
  }

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

      var _this$props5 = this.props,
          closed = _this$props5.closed,
          graphProps = _this$props5.graphProps,
          onChangeLabelProps = _this$props5.onChangeLabelProps,
          points = _this$props5.points,
          middle = _this$props5.middle,
          labelNode = _this$props5.labelNode,
          labelModeEnabled = _this$props5.labelModeEnabled,
          _this$props5$isSoluti = _this$props5.isSolution,
          isSolution = _this$props5$isSoluti === void 0 ? false : _this$props5$isSoluti;
      var polygonLabelIndex = points && points.length || 0;

      if (labelNode && middle && middle.hasOwnProperty('label')) {
        /*#__PURE__*/
        _reactDom["default"].createPortal( /*#__PURE__*/_react["default"].createElement(_markLabel["default"], {
          inputRef: function inputRef(r) {
            return _this2.input[polygonLabelIndex] = r;
          },
          disabled: !labelModeEnabled,
          mark: middle,
          graphProps: graphProps,
          onChange: function onChange(label) {
            return onChangeLabelProps(_objectSpread(_objectSpread({}, middle), {}, {
              label: label
            }));
          }
        }), labelNode);
      }

      return /*#__PURE__*/_react["default"].createElement("g", null, /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_polygon["default"], {
        points: points,
        closed: closed,
        isSolution: isSolution,
        graphProps: graphProps,
        onClick: this.clickPoint.bind(this, middle, polygonLabelIndex)
      })));
    }
  }]);
  return RawBaseComponent;
}(_react["default"].Component);

exports.RawBaseComponent = RawBaseComponent;
(0, _defineProperty2["default"])(RawBaseComponent, "propTypes", {
  classes: _propTypes["default"].object,
  className: _propTypes["default"].string,
  disabled: _propTypes["default"].bool,
  correctness: _propTypes["default"].string,
  points: _propTypes["default"].arrayOf(_plot.types.PointType),
  closed: _propTypes["default"].bool,
  isSolution: _propTypes["default"].bool,
  coordinatesOnHover: _propTypes["default"].bool,
  onChange: _propTypes["default"].func.isRequired,
  onClosePolygon: _propTypes["default"].func.isRequired,
  onDragStart: _propTypes["default"].func,
  onDragStop: _propTypes["default"].func,
  onClick: _propTypes["default"].func,
  graphProps: _plot.types.GraphPropsType.isRequired,
  isToolActive: _propTypes["default"].bool,
  middle: _propTypes["default"].object,
  labelNode: _propTypes["default"].object,
  labelModeEnabled: _propTypes["default"].bool,
  onChangeLabelProps: _propTypes["default"].func,
  onChangeProps: _propTypes["default"].func
});
(0, _defineProperty2["default"])(RawBaseComponent, "defaultProps", {
  points: []
});
var BaseComponent = (0, _styles.withStyles)(function () {
  return {};
})(RawBaseComponent);
exports.BaseComponent = BaseComponent;

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

  var _super2 = _createSuper(Component);

  function Component(props) {
    var _this3;

    (0, _classCallCheck2["default"])(this, Component);
    _this3 = _super2.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "change", function (points) {
      var middle = _this3.props.mark.middle;

      var mark = _objectSpread(_objectSpread({}, _this3.state.mark), {}, {
        points: points
      });

      if (middle) {
        var _getRightestPoints2 = (0, _utils.getRightestPoints)(points),
            a = _getRightestPoints2.a,
            b = _getRightestPoints2.b;

        mark.middle = _objectSpread(_objectSpread({}, middle), (0, _utils.getMiddleOfTwoPoints)(a, b));
      }

      _this3.setState({
        mark: mark
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "changeProps", function (points) {
      var mark = _objectSpread(_objectSpread({}, _this3.props.mark), {}, {
        points: points
      });

      _this3.props.onChange(_this3.props.mark, mark);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "changeLabelProps", function (point) {
      var _this3$props = _this3.props,
          mark = _this3$props.mark,
          onChange = _this3$props.onChange;

      var middle = _objectSpread(_objectSpread({}, mark.middle), point);

      onChange(mark, _objectSpread(_objectSpread({}, mark), {}, {
        middle: middle
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "closePolygon", function () {
      log('[closePolygon] ...');
      var _this3$props2 = _this3.props,
          onComplete = _this3$props2.onComplete,
          mark = _this3$props2.mark;

      var update = _objectSpread(_objectSpread({}, mark), {}, {
        closed: true
      });

      onComplete(mark, update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "dragStart", function () {
      return _this3.setState({
        mark: _this3.props.mark
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "dragStop", function () {
      var onChange = _this3.props.onChange;

      var m = _objectSpread({}, _this3.state.mark);

      _this3.setState({
        mark: undefined
      }, function () {
        onChange(_this3.props.mark, m);
      });
    });
    _this3.state = {};
    return _this3;
  }

  (0, _createClass2["default"])(Component, [{
    key: "render",
    value: function render() {
      var _this$props6 = this.props,
          coordinatesOnHover = _this$props6.coordinatesOnHover,
          mark = _this$props6.mark,
          graphProps = _this$props6.graphProps,
          onClick = _this$props6.onClick,
          isToolActive = _this$props6.isToolActive,
          labelNode = _this$props6.labelNode,
          labelModeEnabled = _this$props6.labelModeEnabled;
      var stateMark = this.state.mark;
      return /*#__PURE__*/_react["default"].createElement(BaseComponent, (0, _extends2["default"])({}, stateMark || mark, {
        coordinatesOnHover: coordinatesOnHover,
        onChange: this.change,
        onChangeLabelProps: this.changeLabelProps,
        onChangeProps: this.changeProps,
        onClosePolygon: this.closePolygon,
        onDragStart: this.dragStart,
        onDragStop: this.dragStop,
        onClick: onClick,
        graphProps: graphProps,
        isToolActive: isToolActive,
        labelNode: labelNode,
        labelModeEnabled: labelModeEnabled
      }));
    }
  }]);
  return Component;
}(_react["default"].Component);

exports["default"] = Component;
(0, _defineProperty2["default"])(Component, "propTypes", _objectSpread(_objectSpread({}, _types.ToolPropTypeFields), {}, {
  graphProps: _plot.types.GraphPropsType.isRequired
}));
(0, _defineProperty2["default"])(Component, "defaultProps", {});
//# sourceMappingURL=component.js.map