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

import React, { useContext, useEffect, useMemo, useState } from 'react';
import clsx from 'clsx';
import { isObject, getSizeStyle } from '../utils';
import { cancelRaf, raf } from '../utils/raf';
import useMergedState from '../hooks/use-merged-state';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
var uid = 0;

function format(rate) {
  return Math.min(Math.max(+rate, 0), 100);
}

function getPath(clockwise, viewBoxSize) {
  var sweepFlag = clockwise ? 1 : 0;
  return "M " + viewBoxSize / 2 + " " + viewBoxSize / 2 + " m 0, -500 a 500, 500 0 1, " + sweepFlag + " 0, 1000 a 500, 500 0 1, " + sweepFlag + " 0, -1000";
}

var ROTATE_ANGLE_MAP = {
  top: 0,
  right: 90,
  bottom: 180,
  left: 270
};

var Circle = function Circle(props) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('circle', prefixCls),
      bem = _createNamespace[0]; // eslint-disable-next-line no-plusplus


  var id = "van-circle-" + uid++;

  var _useState = useState(function () {
    return props.defaultRate || 0;
  }),
      currentRate = _useState[0],
      setCurrentRate = _useState[1];

  var _useMergedState = useMergedState({
    defaultValue: props.defaultRate,
    value: props.rate
  }),
      current = _useMergedState[0];

  var viewBoxSize = useMemo(function () {
    return +props.strokeWidth + 1000;
  }, [props.strokeWidth]);
  var path = useMemo(function () {
    return getPath(props.clockwise, viewBoxSize);
  }, [props.clockwise, viewBoxSize]);
  var svgStyle = useMemo(function () {
    var angleValue = ROTATE_ANGLE_MAP[props.startPosition];

    if (angleValue) {
      return {
        transform: "rotate(" + angleValue + "deg)"
      };
    }

    return undefined;
  }, [props.startPosition]);
  useEffect(function () {
    var rafId;
    var startTime = Date.now();
    var startRate = currentRate;
    var endRate = format(current);
    var duration = Math.abs((startRate - endRate) * 1000 / +props.speed);

    var animate = function animate() {
      var now = Date.now();
      var progress = Math.min((now - startTime) / duration, 1);
      var rate = progress * (endRate - startRate) + startRate;
      var crate = format(parseFloat(rate.toFixed(1)));
      setCurrentRate(crate);

      if (endRate > startRate ? rate < endRate : rate > endRate) {
        rafId = raf(animate);
      } else {
        props.onChange == null ? void 0 : props.onChange(crate);
      }
    };

    if (props.speed) {
      if (rafId) {
        cancelRaf(rafId);
      }

      rafId = raf(animate);
    } else {
      setCurrentRate(endRate);
    }
  }, [current]);

  var renderHover = function renderHover() {
    var PERIMETER = 3140;
    var strokeWidth = props.strokeWidth;
    var offset = PERIMETER * currentRate / 100;
    var color = isObject(props.color) ? "url(#" + id + ")" : props.color;
    var style = {
      stroke: color,
      strokeWidth: +strokeWidth + 1 + "px",
      strokeLinecap: props.strokeLinecap,
      strokeDasharray: offset + "px " + PERIMETER + "px"
    };
    return /*#__PURE__*/React.createElement("path", {
      d: path,
      style: style,
      className: clsx(bem('hover')),
      stroke: color
    });
  };

  var renderLayer = function renderLayer() {
    var style = {
      fill: props.fill,
      stroke: props.layerColor,
      strokeWidth: props.strokeWidth + "px"
    };
    return /*#__PURE__*/React.createElement("path", {
      className: clsx(bem('layer')),
      style: style,
      d: path
    });
  };

  var renderGradient = function renderGradient() {
    var color = props.color;

    if (!isObject(color)) {
      return null;
    }

    var Stops = Object.keys(color).sort(function (a, b) {
      return parseFloat(a) - parseFloat(b);
    }) // eslint-disable-next-line react/no-array-index-key
    .map(function (key, index) {
      return /*#__PURE__*/React.createElement("stop", {
        key: index,
        offset: key,
        stopColor: color[key]
      });
    });
    return /*#__PURE__*/React.createElement("defs", null, /*#__PURE__*/React.createElement("linearGradient", {
      id: id,
      x1: "100%",
      y1: "0%",
      x2: "0%",
      y2: "0%"
    }, Stops));
  };

  var renderText = function renderText() {
    if (props.text) {
      return /*#__PURE__*/React.createElement("div", {
        className: clsx(bem('text'))
      }, props.text);
    }

    return props.children;
  };

  return /*#__PURE__*/React.createElement("div", {
    className: clsx(bem(), props.className),
    style: _extends({}, props.style, getSizeStyle(props.size))
  }, /*#__PURE__*/React.createElement("svg", {
    viewBox: "0 0 " + viewBoxSize + " " + viewBoxSize,
    style: svgStyle
  }, renderGradient(), renderLayer(), renderHover()), renderText());
};

Circle.defaultProps = {
  clockwise: true,
  speed: 100,
  fill: 'none',
  strokeWidth: 40,
  startPosition: 'top'
};
export default Circle;