import $ from 'dom7';
import Utils from '../../utils/utils';

export default class TouchRipple {
  constructor($el, x, y) {
    const ripple = this;
    if (!$el) return undefined;
    const box = $el[0].getBoundingClientRect();
    const center = {
      x: x - box.left,
      y: y - box.top,
    };
    const width = box.width;
    const height = box.height;
    const diameter = Math.max((((height ** 2) + (width ** 2)) ** 0.5), 48);

    ripple.$rippleWaveEl = $(`<div class="ripple-wave" style="width: ${diameter}px; height: ${diameter}px; margin-top:-${diameter / 2}px; margin-left:-${diameter / 2}px; left:${center.x}px; top:${center.y}px;"></div>`);

    $el.prepend(ripple.$rippleWaveEl);

    /* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
    // ripple._clientLeft = ripple.$rippleWaveEl[0].clientLeft;
    ripple.rippleTransform = `translate3d(${-center.x + (width / 2)}px, ${-center.y + (height / 2)}px, 0) scale(1)`;

    Utils.nextFrame(() => {
      if (!ripple || !ripple.$rippleWaveEl) return;
      ripple.$rippleWaveEl.transform(ripple.rippleTransform);
    });

    return ripple;
  }

  onRemove() {
    let ripple = this;
    if (ripple.$rippleWaveEl) {
      ripple.$rippleWaveEl.remove();
    }
    Object.keys(ripple).forEach((key) => {
      ripple[key] = null;
      delete ripple[key];
    });
    ripple = null;
  }

  remove() {
    const ripple = this;
    if (ripple.removing) return;
    const $rippleWaveEl = this.$rippleWaveEl;
    const rippleTransform = this.rippleTransform;
    let removeTimeout = Utils.nextTick(() => {
      ripple.onRemove();
    }, 400);
    ripple.removing = true;
    $rippleWaveEl
      .addClass('ripple-wave-fill')
      .transform(rippleTransform.replace('scale(1)', 'scale(1.01)'))
      .transitionEnd(() => {
        clearTimeout(removeTimeout);
        Utils.nextFrame(() => {
          $rippleWaveEl
            .addClass('ripple-wave-out')
            .transform(rippleTransform.replace('scale(1)', 'scale(1.01)'));

          removeTimeout = Utils.nextTick(() => {
            ripple.onRemove();
          }, 700);

          $rippleWaveEl.transitionEnd(() => {
            clearTimeout(removeTimeout);
            ripple.onRemove();
          });
        });
      });
  }
}
