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 { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';

export default class RogueBloomShader extends RE.Component {
  @RE.props.num() strength = 1.5;
  @RE.props.num() radius = 0.4;
  @RE.props.num() threshold = 0.85;
  @RE.props.num() exposure = 1;

  composer: EffectComposer;
  bloomPass: UnrealBloomPass;
  outputPass: OutputPass;

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

    let bounds = RE.Runtime.rogueDOMContainer.getBoundingClientRect()
    this.bloomPass = new UnrealBloomPass( new THREE.Vector2( bounds.width, bounds.height ), this.strength, this.radius, this.threshold );
    this.bloomPass.threshold = this.threshold;
    this.bloomPass.strength = this.strength;
    this.bloomPass.radius = this.radius;
    this.composer.addPass( this.bloomPass );

    
    this.outputPass = new OutputPass( THREE.ReinhardToneMapping );
    this.outputPass.toneMappingExposure = Math.pow(this.exposure, 4.0)
    this.composer.addPass( this.outputPass );

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

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

  start() {

  }

  update() {
    if(this.threshold != this.bloomPass.threshold) {
      this.bloomPass.threshold = this.threshold
    }
    if(this.strength != this.bloomPass.strength) {
      this.bloomPass.strength = this.strength
    }
    if(this.radius != this.bloomPass.radius) {
      this.bloomPass.radius = this.radius
    }
    if(Math.pow(this.exposure, 4.0) != this.outputPass.toneMappingExposure ) {
      this.outputPass.toneMappingExposure = Math.pow(this.exposure, 4.0)
    }
  }
}

RE.registerComponent(RogueBloomShader);
        