import { Ob, viewport } from "negl";
import { RepeatWrapping, Vector3, PlaneGeometry } from "three";
import { Water } from "three/examples/jsm/objects/Water";
export default class extends Ob {
  beforeCreateMesh() {
    this.fixed = true;
    this.width = 10000;
    this.posY = this.dataAttrs.posY ? +this.dataAttrs.posY : 0;
  }
  setupVertex() {
    return;
  }
  setupFragment() {
    return;
  }
  setupGeometry() {
    return new PlaneGeometry(this.width, this.width);
  }

  setupUniforms() {
    return {};
  }

  setupMaterial() {
    return;
  }
  setupMesh() {
    const texture = this.texes.get("tex1");

    texture.wrapS = texture.wrapT = RepeatWrapping;

    const options = {
      textureWidth: 512,
      textureHeight: 512,
      waterNormals: texture,
      distortionScale: 45,
      sunDirection: new Vector3(0, 0, 0),
      sunColor: 0xffffff,
      waterColor: 0x39e7fe,
    };

    const mesh = new Water(this.geometry, options);
    mesh.material.uniforms.size.value = 0.1;
    this.material = mesh.material;

    const { y } = this.getWorldPosition(this.rect, viewport);
    mesh.position.y = y;

    const theta = Math.atan(mesh.position.y / viewport.far);
    mesh.rotation.x = -Math.PI / 2 - theta;
    return mesh;
  }
  render() {
    this.mesh.material.uniforms["time"].value += 1.0 / 60.0;
  }
  debug(folder) {
    const waterUniforms = this.mesh.material.uniforms;
    folder
      .addColor(waterUniforms.waterColor, "value")
      .name("water color")
      .listen();
    folder.addColor(waterUniforms.sunColor, "value").name("sun color").listen();
    folder
      .add(waterUniforms.distortionScale, "value", 0, 100, 0.1)
      .name("distortionScale")
      .listen();
    folder.add(waterUniforms.size, "value", 0.1, 10, 0.1).name("size").listen();
    folder
      .add(this.mesh.position, "y", -250, 250, 1)
      .name("position.y")
      .listen()
      .onChange(() => {
        const theta = Math.atan(this.mesh.position.y / viewport.far);
        this.mesh.rotation.x = -Math.PI / 2 - theta;
      });
  }
}
