import {Container} from '@pixi/display';
import {PixiComponent} from '@pixi/react';
import * as particles from '@pixi/particle-emitter';

const EmitterInternal = PixiComponent('Emitter', {
  $$emitter: undefined,
  $$raf: undefined,
  create() {
    return new Container();
  },
  applyProps(container, oldProps, newProps) {
    if (!this.$$emitter) {
      const {onComplete, particle} = newProps;
      this.$$emitter = new particles.Emitter(container, particle);
      this.$$emitter._completeCallback = onComplete;
      let last = Date.now();
      const render = () => {
        this.$$raf = requestAnimationFrame(render);
        const now = Date.now();
        this.$$emitter.update((now - last) / 1000);
        last = now;
      };
      this.$$emitter.emit = true;
      render();
    }
  },
  willUnmount() {
    if (this.$$emitter) {
      this.$$emitter.emit = false;
      cancelAnimationFrame(this.$$raf);
    }
  }
});

export default function Emitter({entity}) {
  const {Emitter} = entity;
  const emitters = [];
  for (const id in Emitter.emitting) {
    const particle = Emitter.emitting[id];
    emitters.push(
      <EmitterInternal
        key={id}
        onComplete={() => {
          delete Emitter.emitting[id];
        }}
        particle={particle}
      />
    );
  }
  return <>{emitters}</>;
}

