import { Globe } from './globe';
import { Renderer } from './renderer';
import { DirectionalLight } from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import './style.css';
import { GUI } from 'dat.gui';

const main = new Renderer();

const dirLight = new DirectionalLight(0xffffff, 1);
dirLight.position.set(10, 10, 10);
main.scene.add(dirLight);

const globe = new Globe(1);
main.resize();
globe.initialize(dirLight).catch(console.error);
main.scene.add(globe);

main.camera.position.set(0, 0, 2);

const control = new OrbitControls(main.camera, main.canvas);

const gui = new GUI();
const atmosGui = gui.addFolder('Atmosphere');
const updateAtmosShader = () => {
  globe.atmosphere.setUniforms(globe.atmosphere.shader);
  globe.atmosphere.setUniforms(globe.earthMaterial!);
};
// any's because for some reason the generic expects a string indexed record
atmosGui
  .add<any>(globe.atmosphere.Wavelength, 'x', 0, 1)
  .name('R')
  .onChange(updateAtmosShader);
atmosGui
  .add<any>(globe.atmosphere.Wavelength, 'y', 0, 1)
  .name('G')
  .onChange(updateAtmosShader);
atmosGui
  .add<any>(globe.atmosphere.Wavelength, 'z', 0, 1)
  .name('B')
  .onChange(updateAtmosShader);

atmosGui
  .add<any>(globe.atmosphere, 'thickness', 0.001, 0.5)
  .name('Thickness')
  .onChange(updateAtmosShader);
atmosGui
  .add<any>(globe.atmosphere, 'ScaleDepth', 0.01, 1)
  .name('Scale depth')
  .onChange(updateAtmosShader);
atmosGui
  .add<any>(globe.atmosphere, 'Rayleigh', 0.0001, 0.01)
  .onChange(updateAtmosShader);
atmosGui
  .add<any>(globe.atmosphere, 'Mie', 0.0001, 0.01)
  .onChange(updateAtmosShader);
atmosGui
  .add<any>(globe.atmosphere, 'Exposure', 0, 100)
  .onChange(updateAtmosShader);
atmosGui.open();

const planetGui = gui.addFolder('Planet');
planetGui
  .add<any>(globe.rotation, 'x', -Math.PI * 2, Math.PI * 2, 0.01)
  .name('Rotation X');
planetGui
  .add<any>(globe.rotation, 'y', -Math.PI * 2, Math.PI * 2, 0.01)
  .name('Rotation Y');
planetGui
  .add<any>(globe.rotation, 'z', -Math.PI * 2, Math.PI * 2, 0.01)
  .name('Rotation Z');
// planetGui.add<any>(globe, 'radius', 1, 100).name('Radius');
planetGui.open();

function tick() {
  requestAnimationFrame(tick);
  control.update();
  // globe.rotateY(Math.PI * 0.0005);
  main.render();
  globe.tick();
}

window.addEventListener('resize', () => main.resize());
document.querySelector('#app')?.appendChild(main.canvas);
tick();
