<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Kaltura AFrame Proof of Concept</title>

  <link rel="stylesheet" href="stylesheets/kaltura-theme.css">
  <link rel="stylesheet" href="stylesheets/style.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
  <script src="./three.min.js"></script>
  <script type="text/javascript"
    src="https://cdnapisec.kaltura.com/p/<%=process.env.PARTNER_ID%>/embedPlaykitJs/uiconf_id/<%=process.env.PLAYER_ID%>"></script>

  <script>
    var video, videoImage, videoImageContext, videoTexture, player;

    AFRAME.registerComponent("3dvid", {
      schema: {
        color: { default: "green" },
        size: { type: "int", default: 5 },
        position: { type: "vec3", default: { x: 0, y: 0, z: 0 } },
        rotation: { type: "vec3", default: { x: 20, y: 40, z: 25 } },
      },
      init: function () {
        // sets a-box color to green
        this.el.setAttribute("color", this.data.color);
        // color coding debugging. if the a-box color is
        // green : there was an error in init script
        // white : the video either finished (no loop) or did not load
        // first frame of video : autoplay did not initiate and needs to have manual click
        // random frame in video : for live video playback, the stream stopped

        //instantiate player
        try {
          const config = {
            playback: {
              autoplay: true,
              allowMutedAutoPlay: true
            },
            log: { level: "DEBUG" },
            targetId: "video-player",
            provider: {
              partnerId: "<%=process.env.PARTNER_ID%>",
              uiConfId: "<%=process.env.PLAYER_ID%>",
              ks: "<%=process.env.KS%>"
            },
            text: {
              useNativeTextTrack: true
            }
          };
          player = KalturaPlayer.setup(config);
        } catch (e) {
          console.error(e.message);
        }

        player.loadMedia({ entryId: '<%=process.env.ENTRY_ID%>' });
        player.crossOrigin = "anonymous";

        player.ready().then((res) => {
          // create canvas where the images of video are going to be drawn
          videoImage = document.createElement("canvas");
          videoImage.width = 1280;
          videoImage.height = 720;
          videoImageContext = videoImage.getContext("2d");

          videoImageContext.fillStyle = "#000000";
          videoImageContext.fillRect(0, 0, videoImage.width, videoImage.height);

          // setup text parameters for subtitles
          videoImageContext.font = "50px Arial";
          videoImageContext.textAlign = "center";
          videoImageContext.textBaseline = "middle";

          // create threejs texture which is mapping canvas to texture
          videoTexture = new THREE.Texture(videoImage);
          videoTexture.minFilter = THREE.LinearFilter;
          videoTexture.magFilter = THREE.LinearFilter;

          // create material from texture
          var movieMaterial = new THREE.MeshBasicMaterial({
            map: videoTexture,
            side: THREE.DoubleSide,
          });

          // assign material to this object's mash
          this.el.getObject3D("mesh").material = movieMaterial;
        });

      },
      update: function () { },
      tick: function () {
        // on every frame, check if new video frame is loaded and draw the image onto canvas
        // protect against race conditions where videoImageContext or player.getVideoElement()
        // not defined yet
        if (!player.paused
          && videoImageContext
          && player.getVideoElement()) {

          // draw video image
          videoImageContext.drawImage(player.getVideoElement(), 0, 0, 1280, 720);
          if (videoTexture) {
            // make sure to tell the video texture that needs update on every frame
            videoTexture.needsUpdate = true;
          }
        }
      },
      remove: function () { },
      pause: function () { },
      play: function () { },
    });

    document.addEventListener('click', function (evt) {
      player.muted = false;
    });

  </script>
</head>

<body>
  <!-- Kaltura Player -->
  <div id="video-player" style="display:none; aspect-ratio:16/9; max-height: 85vh; margin: auto;"></div>
  <div class="center">
    <div id="back2vr" style="display:none;">Return</div>
  </div>
  <a-scene id="mainscene" raycaster cursor="rayOrigin: mouse">
    <!-- some static objects -->
    <a-sky color="#BDC9C1"></a-sky>
    <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
    <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
    <a-sphere position="3 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>

    <!-- The video box-->
    <a-box 3dvid id="vidbox" position="0 2 -4" rotation="20 40 25" width="4" height="2"></a-box>
  </a-scene>

  <script type="text/javascript">
    var targetEl = document.querySelector('#vidbox');
    targetEl.addEventListener('click', function () {
      console.log("VIDBOX");
       //hide aframe scene
      $("#mainscene").hide();
      //show video
      $("#video-player").show();
      //show return button
      $("#back2vr").show();
    });

    $("#back2vr").click(function () {
      $("#video-player").hide();
      $("#back2vr").hide();
      $("#mainscene").show();
    });
  </script>

</body>

</html>