import * as RE from 'rogue-engine';
import * as THREE from 'three';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
import { RenderPixelatedPass } from 'three/examples/jsm/postprocessing/RenderPixelatedPass.js';

export default class RoguePixelShader extends RE.Component {
  @RE.props.num() pixelSize = 8;

  composer: EffectComposer;
  pixelPass: RenderPixelatedPass;

  awake() {
    this.composer = new EffectComposer( RE.Runtime.renderer );
    this.composer.addPass( new RenderPass( RE.Runtime.scene, RE.Runtime.camera ) );

    this.pixelPass = new RenderPixelatedPass(this.pixelSize, RE.Runtime.scene, RE.Runtime.camera);
    let bounds = RE.Runtime.rogueDOMContainer.getBoundingClientRect()
    this.pixelPass.setSize(this.pixelSize, this.pixelSize)
    this.pixelPass.setSize(bounds.width, bounds.height)
    this.composer.addPass( this.pixelPass );

    RE.Runtime.renderFunc = () => {
      this.composer.render(RE.Runtime.deltaTime);
    }

    RE.Runtime.onStop(() => {
      RE.Runtime.renderFunc = () => RE.Runtime.defaultRenderFunc();
    });
  }

  update() {
    if (this.pixelSize !== this.pixelPass.pixelSize) {
      this.pixelPass.setSize(this.pixelSize, this.pixelSize)
    }
  }
}

RE.registerComponent(RoguePixelShader);