"use strict";

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

var _jsxRuntime = require("react/jsx-runtime");

var _handle = require("@enact/core/handle");

var _keymap = require("@enact/core/keymap");

var _hoc = _interopRequireDefault(require("@enact/core/hoc"));

var _validators = require("@enact/ui/internal/validators");

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

var _react = require("react");

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

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

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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

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 _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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

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

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

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

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

var isDown = (0, _keymap.is)('down');
var isUp = (0, _keymap.is)('up');
var validateValueRange = (0, _validators.validateRangeOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator'
});
var validateAngleRange = (0, _validators.validateRangeOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator',
  minName: 'startAngle',
  maxName: 'endAngle'
});
var validateStepValue = (0, _validators.validateSteppedOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator'
});
var validateStepMax = (0, _validators.validateSteppedOnce)(function (props) {
  return props;
}, {
  'component': 'ArcSliderBehaviorDecorator',
  valueName: 'max'
});
/**
 * Adds agate-specific arcSlider behaviors.
 *
 * @class ArcSliderBehaviorDecorator
 * @memberof agate/ArcSlider
 * @hoc
 * @public
 */

var ArcSliderBehaviorDecorator = (0, _hoc["default"])(function (config, Wrapped) {
  var _class, _temp;

  return _temp = _class = /*#__PURE__*/function (_Component) {
    _inherits(_class, _Component);

    var _super = _createSuper(_class);

    function _class(props) {
      var _this;

      _classCallCheck(this, _class);

      _this = _super.call(this, props);

      _this.handleDown = function (_ref) {
        var clientX = _ref.clientX,
            clientY = _ref.clientY;
        var params = {
          x: clientX,
          y: clientY
        };
        (0, _handle.forward)('onDown', params, _this.props);

        if (clientX != null && clientY != null) {
          _this.emitChangeForPosition(params);
        }
      };

      _this.handleDragStart = function (ev) {
        (0, _handle.forward)('onDragStart', ev, _this.props);

        _this.emitChangeForPosition(ev);
      };

      _this.handleDrag = function (ev) {
        (0, _handle.forward)('onDrag', ev, _this.props);

        _this.emitChangeForPosition(ev);
      };

      _this.emitChangeForPosition = function (ev) {
        var componentRef = _this.componentRef.current;

        if (!componentRef) {
          return;
        }

        var _this$props = _this.props,
            endAngle = _this$props.endAngle,
            max = _this$props.max,
            min = _this$props.min,
            radius = _this$props.radius,
            startAngle = _this$props.startAngle,
            step = _this$props.step,
            strokeWidth = _this$props.strokeWidth; // Find the coordinates with respect to the SVG

        var svgPoint = componentRef.createSVGPoint();
        svgPoint.x = ev.x;
        svgPoint.y = ev.y;
        var coordsInSvg = svgPoint.matrixTransform(componentRef.getScreenCTM().inverse());
        var angle = (0, _utils.positionToAngle)(coordsInSvg, radius * 2 - strokeWidth); // get the value based on the angle, min and max

        var value = (0, _utils2.angleToValue)(angle, min, max, startAngle, endAngle); // adjust value based on the step

        if (step) {
          var delta = (value - min) % step;

          if (delta < step / 2) {
            value -= delta;
          } else {
            value += step - delta;
          }
        }

        _this.handleChange(ev, value);
      };

      _this.handleChange = function (ev, value) {
        if (value !== _this.state.value) {
          _this.setState(function () {
            return {
              value: value
            };
          }, function () {
            (0, _handle.forward)('onChange', {
              type: 'onChange',
              value: value
            }, _this.props);
          });
        }

        if (ev.stopPropagation) {
          ev.stopPropagation();
        }
      };

      _this.handleBlur = function () {
        _this.setState({
          isFocused: false
        });
      };

      _this.handleFocus = function () {
        _this.setState({
          isFocused: true
        });
      };

      _this.handleKeyDown = function (ev) {
        var _this$props2 = _this.props,
            disabled = _this$props2.disabled,
            max = _this$props2.max,
            min = _this$props2.min,
            step = _this$props2.step;
        var value = _this.state.value;
        (0, _handle.forward)('onKeyDown', ev, _this.props);

        if (!disabled) {
          if (isDown(ev.keyCode)) {
            _this.handleChange(ev, Math.max(value - step, min));
          } else if (isUp(ev.keyCode)) {
            _this.handleChange(ev, Math.min(value + step, max));
          }
        }
      };

      _this.componentRef = /*#__PURE__*/(0, _react.createRef)();
      _this.state = {
        isFocused: false,
        value: props.value ? props.value : props.min
      };
      return _this;
    }

    _createClass(_class, [{
      key: "render",
      value: function render() {
        if (process.env.NODE_ENV !== "production") {
          var _this$props3 = this.props,
              endAngle = _this$props3.endAngle,
              max = _this$props3.max,
              min = _this$props3.min,
              startAngle = _this$props3.startAngle,
              step = _this$props3.step;
          var valueProps = {
            min: min,
            value: this.state.value || min,
            max: max,
            step: step
          };
          var angleProps = {
            startAngle: startAngle,
            endAngle: endAngle
          };
          validateValueRange(valueProps);
          validateAngleRange(angleProps);
          validateStepValue(valueProps);
          validateStepMax(valueProps);
        }

        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, this.props), {}, {
          componentRef: this.componentRef,
          isFocused: this.state.isFocused,
          onBlur: this.handleBlur,
          onChange: this.handleChange,
          onDown: this.handleDown,
          onDrag: this.handleDrag,
          onDragStart: this.handleDragStart,
          onFocus: this.handleFocus,
          onKeyDown: this.handleKeyDown,
          value: this.state.value
        }));
      }
    }]);

    return _class;
  }(_react.Component), _class.displayName = 'ArcSliderBehaviorDecorator', _class.propTypes =
  /** @lends agate/ArcSlider.ArcSliderBehaviorDecorator.prototype */
  {
    /**
     * Whether or not the component is in a disabled state.
     *
     * @type {Boolean}
     * @public
     */
    disabled: _propTypes["default"].bool,

    /**
     * The end angle(in degrees) of the arc slider.
     *
     * The value should be between 0 and 360 and should be greater than startAngle.
     *
     * @type {Number}
     * @default 250
     * @public
     */
    endAngle: _propTypes["default"].number,

    /**
     * The maximum value of the slider and should be greater than min.
     *
     * @type {Number}
     * @default 100
     * @public
     */
    max: _propTypes["default"].number,

    /**
     * The minimum value of the slider.
     *
     * @type {Number}
     * @default 0
     * @public
     */
    min: _propTypes["default"].number,

    /**
     * Called when value is changed.
     *
     * @type {Function}
     * @public
     */
    onChange: _propTypes["default"].func,

    /**
     * The radius of the arc circle.
     *
     * @type {Number}
     * @default 150
     * @public
     */
    radius: _propTypes["default"].number,

    /**
     * The start angle(in degrees) of the arc slider.
     *
     * The value should be between 0 and 360.
     *
     * @type {Number}
     * @default 30
     * @public
     */
    startAngle: _propTypes["default"].number,

    /**
     * The amount to increment or decrement the value.
     *
     * @type {Number}
     * @default 1
     * @public
     */
    step: _propTypes["default"].number,

    /**
     * The stroke width of the arc slider.
     *
     * @type {Number}
     * @default 6
     * @public
     */
    strokeWidth: _propTypes["default"].number,

    /**
     * The value of the slider.
     *
     * Defaults to the value of `min`.
     *
     * @type {Number}
     * @public
     */
    value: _propTypes["default"].number
  }, _class.defaultProps = {
    endAngle: 250,
    max: 100,
    min: 0,
    radius: 150,
    startAngle: 30,
    step: 1,
    strokeWidth: 6
  }, _temp;
});
exports.ArcSliderBehaviorDecorator = ArcSliderBehaviorDecorator;
var _default = ArcSliderBehaviorDecorator;
exports["default"] = _default;