"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.TraitTile = exports.StyledTrait = 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 _debug = _interopRequireDefault(require("debug"));

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

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

var _reactDnd = require("react-dnd");

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

var _renderUi = require("@pie-lib/render-ui");

var _common = require("./common");

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

var _MoreVert = _interopRequireDefault(require("@material-ui/icons/MoreVert"));

var _Menu = _interopRequireDefault(require("@material-ui/core/Menu"));

var _MenuItem = _interopRequireDefault(require("@material-ui/core/MenuItem"));

var _DragIndicator = _interopRequireDefault(require("@material-ui/icons/DragIndicator"));

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-element:placement-ordering:configure:trait-tile');

var styles = function styles(theme) {
  return {
    actions: {
      color: _renderUi.color.text()
    },
    primaryBlock: {
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'space-between',
      marginBottom: theme.spacing.unit * 5
    },
    controls: {
      display: 'flex',
      alignItems: 'center',
      width: '100%',
      cursor: 'pointer'
    },
    options: {
      marginLeft: 'auto'
    },
    dragHandle: {},
    removeLabel: {
      display: 'flex',
      whiteSpace: 'break-spaces'
    },
    errorText: {
      fontSize: theme.typography.fontSize - 2,
      color: theme.palette.error.main,
      paddingBottom: theme.spacing.unit
    }
  };
};

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

  var _super = _createSuper(TraitTile);

  function TraitTile() {
    var _this;

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

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

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", {});
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTraitChanged", function (params) {
      var _this$props = _this.props,
          trait = _this$props.trait,
          onTraitChanged = _this$props.onTraitChanged;
      if ((0, _isEmpty["default"])(params)) return;
      Object.keys(params).forEach(function (key) {
        trait[key] = params[key];
      });
      onTraitChanged(trait);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onScorePointDescriptorChange", function (_ref) {
      var descriptor = _ref.descriptor,
          value = _ref.value;
      var scorePointsDescriptors = _this.props.trait.scorePointsDescriptors;
      if (value < 0 || value >= scorePointsDescriptors.length) return;
      scorePointsDescriptors[value] = descriptor;

      _this.onTraitChanged({
        scorePointsDescriptors: scorePointsDescriptors
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleClick", function (event) {
      return _this.setState({
        anchorEl: event.currentTarget
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleClose", function () {
      return _this.setState({
        anchorEl: null
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "scrollToPosition", function (position) {
      return _this.secondaryBlock.scrollTo({
        left: position
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "openMenu", function () {
      _this.props.onTraitRemoved();

      _this.handleClose();
    });
    return _this;
  }

  (0, _createClass2["default"])(TraitTile, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if (nextProps.currentPosition !== this.props.currentPosition || this.secondaryBlock && this.secondaryBlock.scrollLeft !== nextProps.currentPosition) {
        this.scrollToPosition(nextProps.currentPosition);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props2 = this.props,
          classes = _this$props2.classes,
          connectDragSource = _this$props2.connectDragSource,
          connectDropTarget = _this$props2.connectDropTarget,
          connectDragPreview = _this$props2.connectDragPreview,
          error = _this$props2.error,
          _this$props2$trait = _this$props2.trait,
          name = _this$props2$trait.name,
          standards = _this$props2$trait.standards,
          description = _this$props2$trait.description,
          scorePointsDescriptors = _this$props2$trait.scorePointsDescriptors,
          traitLabel = _this$props2.traitLabel,
          scorePointsValues = _this$props2.scorePointsValues,
          showStandards = _this$props2.showStandards,
          showDescription = _this$props2.showDescription,
          enableDragAndDrop = _this$props2.enableDragAndDrop,
          currentPosition = _this$props2.currentPosition,
          secondaryBlockWidth = _this$props2.secondaryBlockWidth,
          spellCheck = _this$props2.spellCheck,
          maxPoints = _this$props2.maxPoints,
          uploadSoundSupport = _this$props2.uploadSoundSupport,
          _this$props2$mathMlOp = _this$props2.mathMlOptions,
          mathMlOptions = _this$props2$mathMlOp === void 0 ? {} : _this$props2$mathMlOp,
          _this$props2$expanded = _this$props2.expandedPluginProps,
          expandedPluginProps = _this$props2$expanded === void 0 ? {} : _this$props2$expanded,
          _this$props2$labelPlu = _this$props2.labelPluginProps,
          labelPluginProps = _this$props2$labelPlu === void 0 ? {} : _this$props2$labelPlu,
          _this$props2$imageSup = _this$props2.imageSupport,
          imageSupport = _this$props2$imageSup === void 0 ? {} : _this$props2$imageSup;
      var anchorEl = this.state.anchorEl;
      return connectDragPreview(connectDropTarget( /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_common.Row, null, /*#__PURE__*/_react["default"].createElement(_common.PrimaryBlock, {
        className: classes.primaryBlock
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.controls
      }, enableDragAndDrop ? connectDragSource( /*#__PURE__*/_react["default"].createElement("span", {
        className: classes.dragHandle
      }, /*#__PURE__*/_react["default"].createElement(_DragIndicator["default"], {
        className: classes.actions
      }))) : null, /*#__PURE__*/_react["default"].createElement(_IconButton["default"], {
        className: classes.options,
        "aria-label": "more",
        "aria-controls": "long-menu",
        "aria-haspopup": "true",
        onClick: this.handleClick
      }, /*#__PURE__*/_react["default"].createElement(_MoreVert["default"], null)), /*#__PURE__*/_react["default"].createElement(_Menu["default"], {
        id: "long-menu",
        anchorEl: anchorEl,
        keepMounted: true,
        open: !!anchorEl,
        onClose: this.handleClose
      }, /*#__PURE__*/_react["default"].createElement(_MenuItem["default"], {
        onClick: this.openMenu
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.removeLabel,
        dangerouslySetInnerHTML: {
          __html: "Remove ".concat(name || traitLabel)
        }
      })))), /*#__PURE__*/_react["default"].createElement(_common.UnderlinedInput, {
        markup: name,
        error: (error === null || error === void 0 ? void 0 : error.name) || '',
        onChange: function onChange(name) {
          return _this2.onTraitChanged({
            name: name
          });
        },
        pluginProps: labelPluginProps,
        placeholder: "Enter ".concat(traitLabel),
        spellCheck: spellCheck,
        uploadSoundSupport: uploadSoundSupport,
        mathMlOptions: mathMlOptions,
        imageSupport: imageSupport
      }), error && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, error.name || '')), /*#__PURE__*/_react["default"].createElement(_common.SecondaryBlock, {
        setRef: function setRef(ref) {
          _this2.secondaryBlock = ref;
        },
        width: "".concat(secondaryBlockWidth, "px")
      }, showStandards && standards && /*#__PURE__*/_react["default"].createElement(_common.Block, null, /*#__PURE__*/_react["default"].createElement(_common.ExpandedInput, {
        placeholder: "Standards",
        markup: standards.join(','),
        onChange: function onChange(standards) {
          return _this2.onTraitChanged({
            standards: standards.split(',')
          });
        },
        pluginProps: expandedPluginProps,
        spellCheck: spellCheck,
        uploadSoundSupport: uploadSoundSupport,
        mathMlOptions: mathMlOptions,
        imageSupport: imageSupport
      })), showDescription && /*#__PURE__*/_react["default"].createElement(_common.Block, null, /*#__PURE__*/_react["default"].createElement(_common.ExpandedInput, {
        placeholder: "Enter Description",
        markup: description,
        error: (error === null || error === void 0 ? void 0 : error.description) || '',
        onChange: function onChange(description) {
          return _this2.onTraitChanged({
            description: description
          });
        },
        pluginProps: expandedPluginProps,
        spellCheck: spellCheck,
        uploadSoundSupport: uploadSoundSupport,
        mathMlOptions: mathMlOptions,
        imageSupport: imageSupport
      }), error && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, error.description || '')), (scorePointsValues || []).map(function (scorePointsValue, index) {
        var adjustedBlockWidth = _common.BlockWidth + 2 * 8; // 8 is padding

        var remainingSpace = secondaryBlockWidth - adjustedBlockWidth * index + currentPosition - 98;
        var value = scorePointsValues.length - index - 1;
        var scoreDescriptor;

        try {
          scoreDescriptor = scorePointsDescriptors[value] || '';
        } catch (e) {
          scoreDescriptor = '';
        }

        return /*#__PURE__*/_react["default"].createElement(_common.Block, {
          key: "key-key-".concat(index)
        }, /*#__PURE__*/_react["default"].createElement(_common.ExpandedInput, {
          placeholder: "Enter Descriptor",
          markup: scoreDescriptor,
          onChange: function onChange(descriptor) {
            return _this2.onScorePointDescriptorChange({
              descriptor: descriptor,
              value: value
            });
          },
          pluginProps: expandedPluginProps,
          alignToRight: remainingSpace < 296 && scorePointsValue < maxPoints // 296 is the space required for the toolbar
          ,
          spellCheck: spellCheck,
          uploadSoundSupport: uploadSoundSupport,
          mathMlOptions: mathMlOptions,
          imageSupport: imageSupport
        }));
      }))))));
    }
  }]);
  return TraitTile;
}(_react["default"].Component);

exports.TraitTile = TraitTile;
(0, _defineProperty2["default"])(TraitTile, "propTypes", {
  spellCheck: _propTypes["default"].bool,
  uploadSoundSupport: _propTypes["default"].object
});
TraitTile.propTypes = {
  connectDragSource: _propTypes["default"].func.isRequired,
  connectDropTarget: _propTypes["default"].func.isRequired,
  connectDragPreview: _propTypes["default"].func.isRequired,
  classes: _propTypes["default"].object.isRequired,
  error: _propTypes["default"].object,
  isDragging: _propTypes["default"].bool.isRequired,
  id: _propTypes["default"].any,
  isOver: _propTypes["default"].bool,
  index: _propTypes["default"].number,
  onTraitChanged: _propTypes["default"].func.isRequired,
  onTraitRemoved: _propTypes["default"].func.isRequired,
  trait: _propTypes["default"].shape({
    name: _propTypes["default"].string,
    standards: _propTypes["default"].arrayOf(_propTypes["default"].string),
    scorePointsDescriptors: _propTypes["default"].arrayOf(_propTypes["default"].string),
    description: _propTypes["default"].string
  }),
  traitLabel: _propTypes["default"].string,
  scorePointsValues: _propTypes["default"].arrayOf(_propTypes["default"].number),
  showStandards: _propTypes["default"].bool,
  showDescription: _propTypes["default"].bool,
  maxPoints: _propTypes["default"].number,
  enableDragAndDrop: _propTypes["default"].bool,
  currentPosition: _propTypes["default"].number,
  secondaryBlockWidth: _propTypes["default"].number,
  expandedPluginProps: _propTypes["default"].object,
  labelPluginProps: _propTypes["default"].object,
  imageSupport: _propTypes["default"].shape({
    add: _propTypes["default"].func.isRequired,
    "delete": _propTypes["default"].func.isRequired
  })
};
var StyledTrait = (0, _styles.withStyles)(styles)(TraitTile);
exports.StyledTrait = StyledTrait;
var NAME = 'trait-config';
var traitSource = {
  beginDrag: function beginDrag(props) {
    return {
      name: props.trait.name,
      index: props.index
    };
  }
};
var StyledSource = (0, _reactDnd.DragSource)(NAME, traitSource, function (connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    isDragging: monitor.isDragging()
  };
})(StyledTrait);
var traitTarget = {
  hover: function hover() {
    log('[hover]');
  },
  drop: function drop(props, monitor) {
    var item = monitor.getItem();
    log('[drop] item: ', item, 'didDrop?', monitor.didDrop());
    props.onTraitDropped(item, props.index);
  }
};
var StyledSourceAndTarget = (0, _reactDnd.DropTarget)(NAME, traitTarget, function (connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver()
  };
})(StyledSource);
var _default = StyledSourceAndTarget;
exports["default"] = _default;
//# sourceMappingURL=trait.js.map