<template>
  <div class="weh">
    <div class="star-model">
      <canvas
        :style="{
          filter: `drop-shadow(0 0 24px ${color}) drop-shadow(0 0 30px white)`,
        }"
        id="can"
      />
    </div>
  </div>
</template>

<script setup lang="js">
import * as THREE from "three";
import { onMounted } from "vue";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { StarShader } from '../scripts/star_shader';
import { getRGB } from '../scripts/convert_color';

const props = defineProps({
  kind: { type: String, required: true },
  color: { type: String, required: true},
});

onMounted(async () => {
  const canvas = document.getElementById("can");
  const loader = new GLTFLoader();
  const renderer = new THREE.WebGLRenderer({ canvas: canvas ?? undefined });
  renderer.setClearAlpha(0.0);
  const scene = new THREE.Scene();
  const model = await loader.loadAsync(`/models/${props.kind}.gltf`);
  const clock = new THREE.Clock();
  model.scene.traverse((child) => {
    if (child.isMesh) {
      child.material = new THREE.MeshToonMaterial({
        map: child.map != undefined ? child.map : null,
        color: child.material.color,
      });
      scene.add(model.scene);
    }
  });
  const camera = new THREE.PerspectiveCamera(10);
  camera.position.z = 20;

  // set up light
  const rightLight = new THREE.PointLight(0xd1aaf0);
  rightLight.position.set(5, 5, 5);
  rightLight.intensity = 100;
  scene.add(rightLight);

  const leftLight = new THREE.PointLight(0xaaf0d1);
  leftLight.position.set(-5, 0, 5);
  leftLight.intensity = 150;
  scene.add(leftLight);

  scene.add(model.scene);
  scene.add(camera);

  function resizeCanvas() {
    const width = canvas?.clientWidth;
    const height = canvas?.clientHeight;

    renderer.setSize(width, height, false);
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
    renderer.setPixelRatio(1 / (width / 125));
  }

  const rgb = getRGB(props.color);
  const starShader = StarShader;
  starShader.uniforms.red.value = rgb[0] / 256;
  starShader.uniforms.green.value = rgb[1] / 256;
  starShader.uniforms.blue.value = rgb[2] / 256;

  console.log(starShader.uniforms);

  const composer = new EffectComposer(renderer);
  composer.addPass(new RenderPass(scene, camera));
  composer.addPass(new ShaderPass( starShader ));

  function animate() {
    model.scene.rotation.y += 0.01;
    model.scene.rotation.z = Math.sin(clock.getElapsedTime()) / 6;
    model.scene.rotation.x = Math.cos(clock.getElapsedTime()) / 5;
    requestAnimationFrame(animate);
    resizeCanvas();
    composer.render();
  }

  resizeCanvas();
  animate();
})
</script>

<style>
canvas {
  width: 100%;
  aspect-ratio: 1/1;
}
</style>
