"use strict";

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

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

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

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

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

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

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

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

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

var _reactInputAutosize = _interopRequireDefault(require("react-input-autosize"));

var _useDebounce = require("./use-debounce");

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

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

var _labelSvgIcon = _interopRequireDefault(require("./label-svg-icon"));

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 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 inputStyles = function inputStyles(theme) {
  return {
    "float": 'right',
    padding: theme.spacing.unit * 0.5,
    borderRadius: '4px',
    fontSize: '10px',
    backgroundColor: _renderUi.color.defaults.WHITE
  };
};

var styles = function styles(theme) {
  return {
    inputStudent: _objectSpread(_objectSpread({}, inputStyles(theme)), {}, {
      padding: '0',
      border: 'none',
      color: 'inherit',
      fontWeight: 'bold'
    }),
    input: {
      "float": 'right',
      padding: theme.spacing.unit * 0.5,
      fontFamily: theme.typography.fontFamily,
      fontSize: '10px',
      border: "solid 1px ".concat(_renderUi.color.defaults.SECONDARY),
      borderRadius: '3px',
      color: _renderUi.color.defaults.PRIMARY_DARK,
      backgroundColor: _renderUi.color.defaults.WHITE
    },
    disabled: {
      border: "solid 1px ".concat(_renderUi.color.defaults.PRIMARY_DARK),
      backgroundColor: _renderUi.color.defaults.WHITE,
      '-webkit-opacity': '1'
    },
    disabledMark: {
      border: "solid 1px ".concat(_renderUi.color.disabled()),
      color: _renderUi.color.disabled(),
      '-webkit-text-fill-color': _renderUi.color.disabled()
    },
    inputCorrect: _objectSpread(_objectSpread({}, inputStyles(theme)), {}, {
      color: _renderUi.color.defaults.CORRECT_WITH_ICON,
      border: "solid 1px ".concat(_renderUi.color.defaults.CORRECT_WITH_ICON)
    }),
    inputIncorrect: _objectSpread(_objectSpread({}, inputStyles(theme)), {}, {
      color: _renderUi.color.defaults.INCORRECT_WITH_ICON,
      border: "solid 1px ".concat(_renderUi.color.defaults.INCORRECT_WITH_ICON)
    }),
    inputMissing: _objectSpread(_objectSpread({}, inputStyles(theme)), {}, {
      color: _renderUi.color.defaults.MISSING_WITH_ICON,
      border: "solid 1px ".concat(_renderUi.color.defaults.MISSING_WITH_ICON),
      fontWeight: 'bold'
    }),
    incorrect: _objectSpread(_objectSpread({}, inputStyles(theme)), {}, {
      color: _renderUi.color.defaults.INCORRECT_WITH_ICON,
      fontWeight: 'bold',
      padding: '0'
    })
  };
};

var position = function position(graphProps, mark) {
  var rect = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    width: 0,
    height: 0
  };
  var scale = graphProps.scale,
      domain = graphProps.domain,
      range = graphProps.range;
  var shift = 5;
  var rightEdge = scale.x(mark.x) + rect.width + shift;
  var bottomEdge = scale.y(mark.y) + rect.height + shift;
  var h = rightEdge >= scale.x(domain.max) ? 'left' : 'right';
  var v = bottomEdge >= scale.y(range.min) ? 'top' : 'bottom';
  return "".concat(v, "-").concat(h);
};

exports.position = position;

var coordinates = function coordinates(graphProps, mark) {
  var rect = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    width: 0,
    height: 0
  };
  var position = arguments.length > 3 ? arguments[3] : undefined;
  var scale = graphProps.scale;
  var shift = 5;

  switch (position) {
    case 'bottom-right':
      return {
        left: scale.x(mark.x) + shift,
        top: scale.y(mark.y) + shift
      };

    case 'bottom-left':
      return {
        left: scale.x(mark.x) - shift - rect.width,
        top: scale.y(mark.y) + shift
      };

    case 'top-left':
      return {
        left: scale.x(mark.x) - shift - rect.width,
        top: scale.y(mark.y) - shift - rect.height
      };

    case 'top-right':
      return {
        left: scale.x(mark.x) + shift,
        top: scale.y(mark.y) - shift - rect.height
      };

    default:
      return {};
  }
};

exports.coordinates = coordinates;

var LabelInput = function LabelInput(_ref2) {
  var _ref = _ref2._ref,
      externalInputRef = _ref2.externalInputRef,
      label = _ref2.label,
      disabled = _ref2.disabled,
      inputClassName = _ref2.inputClassName,
      onChange = _ref2.onChange;
  return /*#__PURE__*/_react["default"].createElement(_reactInputAutosize["default"], {
    inputRef: function inputRef(r) {
      _ref(r);

      externalInputRef(r);
    },
    disabled: disabled,
    inputClassName: inputClassName,
    value: label,
    onChange: onChange
  });
};

var MarkLabel = function MarkLabel(props) {
  var _cn;

  var _useState = (0, _react.useState)(null),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      input = _useState2[0],
      setInput = _useState2[1];

  var _ref = (0, _react.useCallback)(function (node) {
    return setInput(node);
  });

  var mark = props.mark,
      graphProps = props.graphProps,
      classes = props.classes,
      disabled = props.disabled,
      externalInputRef = props.inputRef,
      theme = props.theme;

  var _useState3 = (0, _react.useState)(mark.label),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      label = _useState4[0],
      setLabel = _useState4[1];

  var correctness = mark.correctness,
      correctnesslabel = mark.correctnesslabel,
      correctlabel = mark.correctlabel;

  var onChange = function onChange(e) {
    return setLabel(e.target.value);
  };

  var debouncedLabel = (0, _useDebounce.useDebounce)(label, 200); // useState only sets the value once, to synch props to state need useEffect

  (0, _react.useEffect)(function () {
    setLabel(mark.label);
  }, [mark.label]); // pick up the change to debouncedLabel and save it

  (0, _react.useEffect)(function () {
    if (typeof debouncedLabel === 'string' && debouncedLabel !== mark.label) {
      props.onChange(debouncedLabel);
    }
  }, [debouncedLabel]);
  var rect = input ? input.getBoundingClientRect() : {
    width: 0,
    height: 0
  };
  var pos = position(graphProps, mark, rect);
  var leftTop = coordinates(graphProps, mark, rect, pos);

  var style = _objectSpread({
    position: 'fixed',
    pointerEvents: 'auto',
    display: 'flex',
    alignItems: 'center',
    gap: '3px'
  }, leftTop);

  var secondLabelStyle = _objectSpread(_objectSpread({}, style), {}, {
    top: leftTop.top + 25
  });

  var disabledInput = disabled || mark.disabled;

  var renderInput = function renderInput(inputClass, labelValue) {
    return /*#__PURE__*/_react["default"].createElement(LabelInput, {
      _ref: _ref,
      externalInputRef: externalInputRef,
      label: labelValue,
      disabled: disabledInput,
      inputClassName: (0, _classnames["default"])(inputClass),
      onChange: onChange
    });
  };

  if (correctness === 'correct' && correctnesslabel === 'correct' && correctlabel) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.inputCorrect,
      style: style
    }, /*#__PURE__*/_react["default"].createElement(_labelSvgIcon["default"], {
      type: "correct"
    }), renderInput(classes.inputStudent, correctlabel));
  } // avoid rendering empty label when a correct point without label  was provided


  if (correctness === 'correct' && correctnesslabel === 'correct' && !correctlabel) {
    return null;
  }

  if (correctness === 'correct' && correctnesslabel === 'incorrect') {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.inputIncorrect,
      style: style
    }, /*#__PURE__*/_react["default"].createElement(_labelSvgIcon["default"], {
      type: "incorrect"
    }), label === '' ? /*#__PURE__*/_react["default"].createElement(_labelSvgIcon["default"], {
      type: "empty",
      style: {
        marginLeft: '3px'
      }
    }) : renderInput(classes.inputStudent, label)), /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.inputMissing,
      style: secondLabelStyle
    }, renderInput(classes.inputStudent, correctlabel)));
  }

  if (correctness === 'missing') {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.inputMissing,
      style: style
    }, renderInput(classes.inputStudent, label));
  }

  if (correctness === 'incorrect') {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: classes.incorrect,
      style: style
    }, renderInput(classes.inputStudent, label));
  }

  return /*#__PURE__*/_react["default"].createElement("div", {
    style: style
  }, renderInput((0, _classnames["default"])(classes.input, (_cn = {}, (0, _defineProperty2["default"])(_cn, classes.disabled, disabled), (0, _defineProperty2["default"])(_cn, classes.disabledMark, mark.disabled), _cn)), label));
};

exports.MarkLabel = MarkLabel;
MarkLabel.propTypes = {
  disabled: _propTypes["default"].bool,
  onChange: _propTypes["default"].func,
  graphProps: _plot.types.GraphPropsType,
  classes: _propTypes["default"].object,
  inputRef: _propTypes["default"].func,
  mark: _propTypes["default"].object,
  theme: _propTypes["default"].object
};

var _default = (0, _styles.withStyles)(styles, {
  withTheme: true
})(MarkLabel);

exports["default"] = _default;
//# sourceMappingURL=mark-label.js.map