"use strict";

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

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

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

var _constants = require("./constants");

var _styledComponents = require("./styled-components");

var _overrides = require("../helpers/overrides");

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/* global document */

/* global window */
var Slider =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Slider, _React$Component);

  function Slider() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, Slider);

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

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Slider)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "domNode", void 0);

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      isThumbMoving: false,
      currentThumb: -1,
      currentMove: 0,
      thumbRefs: _this.props.value.map(function () {
        return React.createRef();
      })
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onThumbDown", function (event, thumbIndex) {
      document.addEventListener('mousemove', _this.onMouseMove);
      document.addEventListener('mouseup', _this.onThumbUp);

      _this.setState({
        isThumbMoving: true,
        currentThumb: thumbIndex
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onThumbUp", function (event) {
      var isThumbMoving = _this.state.isThumbMoving;

      if (isThumbMoving) {
        _this.setState({
          isThumbMoving: false,
          currentThumb: -1,
          currentMove: 0
        });
      }

      document.removeEventListener('mousemove', _this.onMouseMove);
      document.removeEventListener('mouseup', _this.onThumbUp);
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onMouseMove", function (event) {
      var isThumbMoving = _this.state.isThumbMoving;

      if (isThumbMoving) {
        _this.onMove(event.movementX, event);
      }
    });

    return _this;
  }

  _createClass(Slider, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      /* eslint-disable-next-line react/no-find-dom-node */
      this.domNode = (0, _reactDom.findDOMNode)(this);
    }
  }, {
    key: "onMove",
    value: function onMove(movementX, event) {
      var _this$state = this.state,
          currentThumb = _this$state.currentThumb,
          currentMove = _this$state.currentMove;
      var _this$props = this.props,
          onChange = _this$props.onChange,
          step = _this$props.step;

      var _this$getSharedProps = this.getSharedProps(),
          $value = _this$getSharedProps.$value,
          $max = _this$getSharedProps.$max,
          $min = _this$getSharedProps.$min,
          $isRange = _this$getSharedProps.$isRange; // add mouse move in pixels to already recorded move in progress


      var newMove = currentMove + movementX; // get move direction factor based on sign of new move

      var moveDirection = newMove / Math.abs(newMove);
      var value = $value.slice();
      var axisSizeInPixels = parseInt(window.getComputedStyle(this.domNode).width);
      var axisSize = $max - $min; // scale step to be measured in pixels

      step = step ? Slider.scale(step, axisSize, axisSizeInPixels) : step;
      var scaledStep = step ? moveDirection * step : newMove;
      var isMoveThresholdPasssed = Math.abs(newMove) - Math.abs(scaledStep) >= 0; // if move detected is larger than step we can move to the next tick

      if (isMoveThresholdPasssed) {
        var scaledMove = Slider.scale(scaledStep, axisSizeInPixels, axisSize); // clamp max and min to avoid overlapping and cross of each other

        var max = !currentThumb && $isRange ? value[1] : $max;
        var min = currentThumb && $isRange ? value[0] : $min;
        value[currentThumb] = Slider.clampIt(value[currentThumb] + scaledMove, max, min);
        this.setState({
          currentMove: 0
        });
      } else {
        // proceed to track the newMove of mouse
        this.setState({
          currentMove: newMove
        });
      }

      onChange({
        event: event,
        value: value
      });
    }
  }, {
    key: "onAxisClick",
    value: function onAxisClick(e) {
      var _this2 = this;

      var value = this.props.value;
      var thumbRefs = this.state.thumbRefs; // only for one thumb feature
      //$FlowFixMe

      if (value.length === 1 && e.currentTarget.parentNode) {
        var thumb = thumbRefs[0].current;
        var axisOffset = e.clientX - e.currentTarget.parentNode.offsetLeft; //$FlowFixMe

        var xPos = axisOffset - thumb.offsetLeft - _constants.thumbWidth;
        this.setState({
          currentThumb: 0
        }, function () {
          _this2.onMove(xPos, e);
        });
      }
    }
  }, {
    key: "getSharedProps",
    value: function getSharedProps() {
      var _this$props2 = this.props,
          range = _this$props2.range,
          value = _this$props2.value;
      var currentThumb = this.state.currentThumb;
      return {
        $value: value,
        $range: range,
        $max: range[range.length - 1],
        $min: range[0],
        $currentThumb: currentThumb,
        $isRange: value.length % 2 === 0
      };
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props3 = this.props,
          _this$props3$override = _this$props3.overrides,
          overrides = _this$props3$override === void 0 ? {} : _this$props3$override,
          range = _this$props3.range,
          value = _this$props3.value;
      var thumbRefs = this.state.thumbRefs;

      var _getOverrides = (0, _overrides.getOverrides)(overrides.Root, _styledComponents.Root),
          _getOverrides2 = _slicedToArray(_getOverrides, 2),
          Root = _getOverrides2[0],
          rootProps = _getOverrides2[1];

      var _getOverrides3 = (0, _overrides.getOverrides)(overrides.Axis, _styledComponents.Axis),
          _getOverrides4 = _slicedToArray(_getOverrides3, 2),
          Axis = _getOverrides4[0],
          axisProps = _getOverrides4[1];

      var _getOverrides5 = (0, _overrides.getOverrides)(overrides.AxisRange, _styledComponents.AxisRange),
          _getOverrides6 = _slicedToArray(_getOverrides5, 2),
          AxisRange = _getOverrides6[0],
          axisRangeProps = _getOverrides6[1];

      var _getOverrides7 = (0, _overrides.getOverrides)(overrides.Thumb, _styledComponents.Thumb),
          _getOverrides8 = _slicedToArray(_getOverrides7, 2),
          Thumb = _getOverrides8[0],
          thumbProps = _getOverrides8[1];

      var _getOverrides9 = (0, _overrides.getOverrides)(overrides.Tick, _styledComponents.Tick),
          _getOverrides10 = _slicedToArray(_getOverrides9, 2),
          Tick = _getOverrides10[0],
          tickProps = _getOverrides10[1];

      var _getOverrides11 = (0, _overrides.getOverrides)(overrides.TickBar, _styledComponents.TickBar),
          _getOverrides12 = _slicedToArray(_getOverrides11, 2),
          TickBar = _getOverrides12[0],
          tickBarProps = _getOverrides12[1];

      var sharedProps = this.getSharedProps();
      return React.createElement(Root, _extends({}, sharedProps, {
        onClick: function onClick(e) {
          return _this3.onAxisClick(e);
        }
      }, rootProps), React.createElement(Axis, _extends({}, sharedProps, axisProps), value.map(function (thumb, $index) {
        return React.createElement(React.Fragment, {
          key: $index
        }, React.createElement(AxisRange, _extends({
          $index: $index
        }, sharedProps, axisRangeProps)), React.createElement(Thumb, _extends({
          $ref: thumbRefs[$index],
          key: $index,
          $index: $index,
          onMouseDown: function onMouseDown(e) {
            return _this3.onThumbDown(e, $index);
          }
        }, sharedProps, thumbProps)));
      })), React.createElement(TickBar, _extends({}, sharedProps, tickBarProps), range.map(function (tick, $index) {
        return React.createElement(Tick, _extends({
          key: $index,
          $index: $index
        }, sharedProps, tickProps), tick);
      })));
    }
  }], [{
    key: "clampIt",
    value: function clampIt(value, max, min) {
      return Math.max(min, Math.min(value, max));
    }
  }, {
    key: "scale",
    value: function scale(x, distanceX, distanceY) {
      return x * distanceY / distanceX;
    }
  }]);

  return Slider;
}(React.Component);

_defineProperty(Slider, "defaultProps", {
  overrides: {},
  onChange: function onChange() {},
  error: false,
  autoFocus: false,
  tabIndex: 0
});

var _default = Slider;
exports.default = _default;