/*
Auto-generated by: https://github.com/pmndrs/gltfjsx
*/

import * as THREE from 'three'
import React, { useRef, useEffect } from 'react'
import { useGLTF } from '@react-three/drei/useGLTF'
import {
  Mesh,
  Color,
  MeshBasicMaterial,
  MeshStandardMaterial,
  VideoTexture,
  DoubleSide,
} from 'three'
import { GLTF } from 'three/examples/jsm/loaders/GLTFLoader'

type GLTFResult = GLTF & {
  nodes: {
    Cube013: Mesh
    ['Cube.013_1']: Mesh
    ['Cube.013_2']: Mesh
    Cube001: THREE.Mesh
    ['Cube.001_1']: THREE.Mesh
    ['Cube.001_2']: THREE.Mesh
  }
  materials: {
    plastic: MeshStandardMaterial
    projection_light: MeshStandardMaterial
    projection: MeshStandardMaterial
  }
}

export default function Model(
  props: JSX.IntrinsicElements['group'] & { videoSrc: string; wide?: boolean },
) {
  const { nodes, materials } = useGLTF(
    `/model/obras/proyector${props.wide ? '_wide' : ''}.glb`,
  ) as GLTFResult
  const group = useRef<THREE.Group>()
  const videoRef = useRef<HTMLVideoElement>(document.createElement('video'))
  const projectionMaterial = useRef<MeshBasicMaterial>(
    new MeshBasicMaterial({ color: new Color('white') }),
  )
  const videoTexture = useRef<VideoTexture>()

  useEffect(() => {
    if (videoRef.current && projectionMaterial) {
      videoRef.current.src = props.videoSrc
      videoRef.current.load()
      videoRef.current.loop = true
      videoRef.current.muted = true
      videoRef.current.autoplay = true
      videoRef.current.play()

      videoTexture.current = new VideoTexture(videoRef.current)
      projectionMaterial.current.map = videoTexture.current
      projectionMaterial.current.needsUpdate = true
    }
  }, [videoRef.current, projectionMaterial.current])

  return (
    <group ref={group} {...props} dispose={null}>
      {!props.wide ? (
        <>
          <mesh material={materials.plastic} geometry={nodes.Cube013.geometry} />
          <mesh
            material={materials.projection_light}
            geometry={nodes['Cube.013_1'].geometry}
          />
          <mesh
            material={projectionMaterial.current}
            geometry={nodes['Cube.013_2'].geometry}
          />
        </>
      ) : (
        <>
          <mesh material={materials.plastic} geometry={nodes.Cube001.geometry} />
          <mesh
            material={materials.projection_light}
            geometry={nodes['Cube.001_1'].geometry}
          />
          <mesh
            material={projectionMaterial.current}
            geometry={nodes['Cube.001_2'].geometry}
          />
        </>
      )}
    </group>
  )
}

useGLTF.preload('/model/obras/proyector.glb')
