/**
 * 脉冲器
 * @alias Pulser
 * @constructor
 *
 * @param {Object} options -脉冲器选项
 */
function Pulser(options) {
  /**
   * 地图对象
   * @type {Map}
   *
   * @summary <mapboxgl.Map>
   */
  let map = options.map;

  /**
   * 脉冲半径
   * @type {Number}
   */
  let size = options.size || 60;

  /**
   * 内圆颜色
   * @type {Object}
   *
   * @summary <{r:red, g:green, b:blue}>
   */
  let innerColor = options.innerColor || {r:255, g:25, b:25};
  /**
   * 外圆颜色
   * @type {Object}
   *
   * @summary <{ r:red, g:green, b:blue}>
   */
  let outerColor = options.outerColor || {r:255, g:50, b:50};

  let pulsingDot = {
    width: size,
    height: size,
    data: new Uint8Array(size * size * 4),

    onAdd: function () {
      let canvas = document.createElement('canvas');
      canvas.width = this.width;
      canvas.height = this.height;
      this.context = canvas.getContext('2d');
    },

    render: function () {
      let duration = 1000;
      let t = (performance.now() % duration) / duration;

      let radius = size / 2 * 0.4;
      let outerRadius = size / 2 * 0.7 * t + radius;
      let context = this.context;

      // draw outer circle
      context.clearRect(0, 0, this.width, this.height);
      context.beginPath();
      context.arc(this.width / 2, this.height / 2, outerRadius, 0, Math.PI * 2);
      context.fillStyle = 'rgba(' + outerColor.r + ', ' + outerColor.g + ', ' + outerColor.b + ',' + (1 - t) + ')';
      context.fill();

      // draw inner circle
      context.beginPath();
      context.arc(this.width / 2, this.height / 2, radius, 0, Math.PI * 2);
      context.fillStyle = 'rgba(' + innerColor.r + ', ' + innerColor.g + ', ' + innerColor.b + ', 0.9)';
      context.strokeStyle = 'rgba(' + outerColor.r + ', ' + outerColor.g + ', ' + outerColor.b + ', 0.8)';
      context.lineWidth = 4 + 4 * (1 - t);
      context.fill();
      context.stroke();

      // update this image's data with data from the canvas
      this.data = context.getImageData(0, 0, this.width, this.height).data;

      // keep the map repainting
      map.triggerRepaint();

      // return `true` to let the map know that the image was updated
      return true;
    }
  };

  return pulsingDot;
}

export default Pulser;
