export class TMRAnimations {

  static withAnimation(sprite, pixiTMR, ...animations) {
    if (animations.length > 0) {
      animations.forEach(animation =>
        pixiTMR.animate(pixiApp => pixiApp.ticker.add(delta => animation(sprite, delta)))
      )
    }
    return sprite
  }

  static rotation(options = { frequence: () => 1, angle: () => 1 }) {
    return (sprite, delta) => {
      if (!sprite.tmrConfig) {
        sprite.tmrConfig = { nextTick: 0 }
      }
      sprite.tmrConfig.nextTick -= delta
      if (sprite.tmrConfig.nextTick <= 0) {
        sprite.tmrConfig.nextTick = options.frequence(delta)
        sprite.angle += options.angle(delta)
      }
    }
  }

  static changeZoom(range = { min: 0.8, max: 1.2, step: 0.005 }) {
    return (sprite, delta) => {
      if (!sprite.tmrConfig) {
        sprite.tmrConfig = TMRAnimations.startRange(range)
      }
      sprite.tmrConfig.current += (sprite.tmrConfig.step * delta)
      if (sprite.tmrConfig.current < sprite.tmrConfig.min) {
        sprite.tmrConfig.step = Math.abs(sprite.tmrConfig.step)
      }
      else if (sprite.tmrConfig.current > sprite.tmrConfig.max) {
        sprite.tmrConfig.step = -Math.abs(sprite.tmrConfig.step)

      }
      const taille = sprite.tmrConfig.current * sprite.taille()
      sprite.width = taille
      sprite.height = taille
    }
  }

  static verticalAxis(options = { step: 1 }) {
    return (sprite, delta) => {
      if (!sprite.tmrConfig) {
        sprite.tmrConfig = this.startRange({
          min: -Math.PI / 2,
          max: Math.PI / 2,
          step: options.step * Math.PI / 180,
        })
      }
      sprite.tmrConfig.current += (sprite.tmrConfig.step * delta)
      sprite.width = Math.cos(sprite.tmrConfig.current) * sprite.taille()
    }
  }

  static startRange(range) {
    range.current = TMRAnimations.randomInSegment(range)
    const min = range.min
    if (min > range.max) {
      range.min = range.max
      range.max = min
    }
    return range
  }

  static outOfRange(range) {
    return range.current < range.min || range.current > range.max
  }

  static randomInSegment(range) {
    const min = range.min
    const max = range.max
    const step = range.step
    return min + (Math.floor(Math.random() / step) * step) * (max - min)
  }
}
