"use strict";

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

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

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

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 _styles = require("@material-ui/core/styles");

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

var _trait = _interopRequireDefault(require("./trait"));

var _ArrowBackIos = _interopRequireDefault(require("@material-ui/icons/ArrowBackIos"));

var _ArrowForwardIos = _interopRequireDefault(require("@material-ui/icons/ArrowForwardIos"));

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 styles = function styles(theme) {
  return {
    wrapper: {
      display: 'flex',
      position: 'relative'
    },
    tableWrapper: {
      width: '100%',
      overflow: 'auto'
    },
    table: {
      borderSpacing: 0,
      marginBottom: theme.spacing.unit * 2,
      borderRadius: '4px',
      color: _renderUi.color.text(),
      fontSize: theme.typography.fontSize,
      lineHeight: '16px',
      overflow: 'unset',
      '& ul, ol': {
        marginBlockStart: 0,
        paddingInlineStart: theme.spacing.unit * 2
      },
      '& th': {
        padding: theme.spacing.unit * 2,
        textAlign: 'left',
        backgroundColor: _renderUi.color.secondaryBackground(),
        verticalAlign: 'bottom'
      },
      '& th div': {
        width: '200px'
      },
      '& td': {
        width: '200px',
        padding: "".concat(theme.spacing.unit * 2, "px ").concat(theme.spacing.unit, "px"),
        verticalAlign: 'top'
      }
    },
    scorePointHeader: {
      '& td': {
        border: 0,
        padding: 0,
        textAlign: 'center',
        minWidth: '200px'
      }
    },
    pointLabel: {
      marginBottom: '4px'
    },
    scorePointValue: {
      fontWeight: 'normal'
    }
  };
};

var ArrowContainer = function ArrowContainer(_ref) {
  var show = _ref.show,
      onClick = _ref.onClick,
      extraStyles = _ref.extraStyles,
      children = _ref.children;
  return /*#__PURE__*/_react["default"].createElement("div", {
    style: _objectSpread({
      height: 'calc(100% - 1px)',
      top: '1px',
      display: show ? 'flex' : 'none',
      width: '50px',
      margin: 'auto',
      position: 'absolute',
      alignItems: 'center',
      justifyContent: 'center',
      cursor: 'pointer'
    }, extraStyles),
    onClick: onClick
  }, children);
};

ArrowContainer.propTypes = {
  show: _propTypes["default"].bool,
  onClick: _propTypes["default"].func,
  extraStyles: _propTypes["default"].object,
  children: _propTypes["default"].object
};

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

  var _super = _createSuper(Scale);

  function Scale() {
    var _this;

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

    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), "scrollLeft", function () {
      _this.tableWrapper.scrollLeft -= _this.tableWrapper.offsetWidth / 2;

      _this.setState({
        showRight: _this.tableWrapper.scrollLeft < _this.tableWrapper.scrollWidth,
        showLeft: _this.tableWrapper.scrollLeft < _this.tableWrapper.scrollWidth && _this.tableWrapper.scrollLeft > 0
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "scrollRight", function () {
      var initialScrollLeft = _this.tableWrapper.scrollLeft;
      _this.tableWrapper.scrollLeft += _this.tableWrapper.offsetWidth / 2;

      _this.setState({
        showRight: initialScrollLeft !== _this.tableWrapper.scrollLeft && _this.tableWrapper.scrollLeft < _this.tableWrapper.scrollWidth,
        showLeft: _this.tableWrapper.scrollLeft < _this.tableWrapper.scrollWidth && _this.tableWrapper.scrollLeft > 0
      });
    });
    return _this;
  }

  (0, _createClass2["default"])(Scale, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.tableWrapper) {
        if (this.tableWrapper.offsetWidth < this.tableWrapper.scrollWidth) {
          this.setState({
            showRight: true
          });
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state = this.state,
          showRight = _this$state.showRight,
          showLeft = _this$state.showLeft;
      var _this$props = this.props,
          classes = _this$props.classes,
          scale = _this$props.scale,
          scaleIndex = _this$props.scaleIndex,
          showDescription = _this$props.showDescription,
          showPointsLabels = _this$props.showPointsLabels,
          showStandards = _this$props.showStandards,
          arrowsDisabled = _this$props.arrowsDisabled;

      var _ref2 = scale || {},
          excludeZero = _ref2.excludeZero,
          maxPoints = _ref2.maxPoints,
          traitLabel = _ref2.traitLabel,
          traits = _ref2.traits,
          scorePointsLabels = _ref2.scorePointsLabels;

      var scorePointsValues = [];
      var descriptions;
      var pointsLabels;
      var standards;

      try {
        // determining the score points values
        for (var pointValue = maxPoints; pointValue >= excludeZero ? 1 : 0; pointValue -= 1) {
          scorePointsValues.push(pointValue);
        }

        var _traits$reduce = traits.reduce(function (tcc, trait) {
          return {
            traitStandards: [].concat((0, _toConsumableArray2["default"])(tcc.traitStandards), (0, _toConsumableArray2["default"])(trait.standards || [])),
            traitDescriptions: [].concat((0, _toConsumableArray2["default"])(tcc.traitDescriptions), (0, _toConsumableArray2["default"])(trait.description || []))
          };
        }, {
          traitStandards: [],
          traitDescriptions: []
        }),
            traitStandards = _traits$reduce.traitStandards,
            traitDescriptions = _traits$reduce.traitDescriptions;

        descriptions = showDescription && traitDescriptions.length;
        pointsLabels = showPointsLabels && scorePointsLabels.length;
        standards = showStandards && traitStandards.length;
      } catch (e) {
        descriptions = false;
        pointsLabels = false;
        standards = false;
      }

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.wrapper
      }, /*#__PURE__*/_react["default"].createElement(ArrowContainer, {
        show: showLeft && !arrowsDisabled,
        onClick: this.scrollLeft,
        extraStyles: {
          left: 0,
          background: "linear-gradient(to right, white, ".concat(_renderUi.color.background(), ")")
        }
      }, /*#__PURE__*/_react["default"].createElement(_ArrowBackIos["default"], null)), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.tableWrapper,
        ref: function ref(_ref3) {
          _this2.tableWrapper = _ref3;
        },
        onScroll: function onScroll() {
          _this2.setState({
            // 5 is a margin of error
            showRight: _this2.tableWrapper.scrollLeft + _this2.tableWrapper.offsetWidth < _this2.tableWrapper.scrollWidth - 5 && _this2.tableWrapper.scrollLeft < _this2.tableWrapper.scrollWidth,
            showLeft: _this2.tableWrapper.scrollLeft < _this2.tableWrapper.scrollWidth && _this2.tableWrapper.scrollLeft > 0
          });
        }
      }, arrowsDisabled && (showRight || showLeft) ? /*#__PURE__*/_react["default"].createElement("div", null, "The item is too large to fit in print mode.") : null, /*#__PURE__*/_react["default"].createElement("table", {
        key: "scale-".concat(scaleIndex),
        className: classes.table
      }, /*#__PURE__*/_react["default"].createElement("thead", null, /*#__PURE__*/_react["default"].createElement("tr", null, /*#__PURE__*/_react["default"].createElement("th", null, /*#__PURE__*/_react["default"].createElement("div", {
        dangerouslySetInnerHTML: {
          __html: traitLabel
        }
      })), standards ? /*#__PURE__*/_react["default"].createElement("th", null, /*#__PURE__*/_react["default"].createElement("div", null, "Standard(s)")) : null, descriptions ? /*#__PURE__*/_react["default"].createElement("th", null, /*#__PURE__*/_react["default"].createElement("div", null, "Description")) : null, scorePointsValues && scorePointsValues.map(function (scorePointValue, index) {
        var pointLabel = ''; // to handle the case when there aren't enough labels

        try {
          pointLabel = scorePointsLabels[scorePointsValues.length - index - 1] || '';
        } catch (e) {
          pointLabel = '';
        }

        return /*#__PURE__*/_react["default"].createElement("th", {
          key: "table-header-".concat(index)
        }, /*#__PURE__*/_react["default"].createElement("table", {
          className: classes.scorePointHeader
        }, /*#__PURE__*/_react["default"].createElement("thead", null, pointsLabels ? /*#__PURE__*/_react["default"].createElement("tr", null, /*#__PURE__*/_react["default"].createElement("td", null, /*#__PURE__*/_react["default"].createElement("div", {
          className: classes.pointLabel,
          dangerouslySetInnerHTML: {
            __html: pointLabel
          }
        }))) : null, /*#__PURE__*/_react["default"].createElement("tr", null, /*#__PURE__*/_react["default"].createElement("td", {
          className: classes.scorePointValue
        }, scorePointValue === 1 ? "".concat(scorePointValue, " point") : "".concat(scorePointValue, " points"))))));
      }))), /*#__PURE__*/_react["default"].createElement("tbody", null, traits && traits.map(function (trait, traitIndex) {
        return /*#__PURE__*/_react["default"].createElement(_trait["default"], {
          key: "trait_".concat(scaleIndex, "_").concat(traitIndex),
          trait: trait,
          traitIndex: traitIndex,
          showDescription: !!descriptions,
          showStandards: !!standards,
          scaleIndex: scaleIndex,
          scorePointsValues: scorePointsValues,
          excludeZero: excludeZero
        });
      })))), /*#__PURE__*/_react["default"].createElement(ArrowContainer, {
        show: showRight && !arrowsDisabled,
        onClick: this.scrollRight,
        extraStyles: {
          right: 0,
          background: "linear-gradient(to left, white, ".concat(_renderUi.color.background(), ")")
        }
      }, /*#__PURE__*/_react["default"].createElement(_ArrowForwardIos["default"], null)));
    }
  }]);
  return Scale;
}(_react["default"].Component);

Scale.propTypes = {
  classes: _propTypes["default"].object,
  scaleIndex: _propTypes["default"].number,
  scale: _propTypes["default"].shape({
    excludeZero: _propTypes["default"].bool,
    maxPoints: _propTypes["default"].number,
    scorePointsLabels: _propTypes["default"].arrayOf(_propTypes["default"].string),
    traitLabel: _propTypes["default"].string,
    traits: _propTypes["default"].arrayOf(_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
    }))
  }),
  showPointsLabels: _propTypes["default"].bool,
  showDescription: _propTypes["default"].bool,
  showStandards: _propTypes["default"].bool,
  arrowsDisabled: _propTypes["default"].bool
};

var _default = (0, _styles.withStyles)(styles)(Scale);

exports["default"] = _default;
//# sourceMappingURL=scale.js.map