<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Amaranth:ital,wght@0,400;0,700;1,400;1,700&family=Kanit:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Oswald:wght@200..700&display=swap"
      rel="stylesheet"
    />

    <!-- for favicon -->
    <link
      rel="apple-touch-icon"
      sizes="180x180"
      href="favicon/apple-touch-icon.png"
    />
    <link
      rel="icon"
      type="image/png"
      sizes="32x32"
      href="favicon/favicon-32x32.png"
    />
    <link
      rel="icon"
      type="image/png"
      sizes="16x16"
      href="favicon/favicon-16x16.png"
    />
    <link rel="manifest" href="/site.webmanifest" />
    <meta name="msapplication-TileColor" content="#da532c" />
    <meta name="theme-color" content="#ffffff" />

    <!--  -->
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Chatters:Video-Chat</title>

    <!-- Stylesheets -->

    <link rel="stylesheet" href="css/main.css" />
    <link rel="stylesheet" href="css/responsive.css" />
    <link rel="stylesheet" href="css/after.css" />
    <link rel="stylesheet" href="css/hover.css" />
    <link rel="stylesheet" href="css/textChat.css" />
    <link rel="stylesheet" href="css/videoChat.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
      integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0"
    />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body style="background-color: #101010">
    <header>
      <!-- nav section -->
      <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
          <a class="navbar-brand" href="/"
            ><img
              class="navChatterLogo"
              src="https://chatters-lhfj.onrender.com/res/imgs/logo2.svg"
              alt="banner"
          /></a>
          <button
            class="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarNavAltMarkup"
            aria-controls="navbarNavAltMarkup"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
            <span class="material-symbols-outlined navbar-toggler-icon">
              density_medium
            </span>
          </button>
          <div
            class="routesDiv collapse navbar-collapse"
            id="navbarNavAltMarkup"
          >
            <div class="routes navbar-nav">
              <a
                class="green green-hover-underline-animation nav-link"
                aria-current="page"
                href="/home"
                >Home</a
              >
              <a
                class="neonBlue neonBlue-hover-underline-animation nav-link"
                href="/text-chat"
                >Text</a
              >

              <div class="loginButtonDiv">
                <form method="get" action="/login">
                  <button style="visibility: hidden;" type="submit" class="login">Login</button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </nav>
    </header>
    <main style="padding-top: 0px;">
      <div  class="mainScreen">
        <video class="you"></video>
        <video class="stranger"></video>
      </div>
      <div class="buttonDiv">

        <button class="newSkipButton new">New</button>
      </div>
    </main>
    
    <script src="/js/onClick.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script javascript>
      const new_skipButton = document.querySelector(".newSkipButton");

      const socket = io();
      socket.disconnect();

      const options = {
        mime: "video/webm",
      };
      const yourVideo = document.querySelector(".you");
      const strangerVideo = document.querySelector(".stranger");
      yourVideo.muted = true;
      // yourVideo.controls=true;

      // function to add video To screen
      function addVideoStream(video, stream) {
        video.srcObject = stream;
        video.addEventListener("loadedmetadata", () => {
          video.play();
        });
      }
      // checking or getting permissions
    if( navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true,
        })){

          navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true,
        }).then((stream) => {
            // added our video to the screen
          addVideoStream(yourVideo, stream);
          

          const media = new MediaRecorder(stream, options);

// media.ondataavailable = function (e) {
//   socket.emit("stream", e.data);

//   // console.log("data coming from seever",e);
// };

// media.start(100);
});

}
new_skipButton.addEventListener("click", () => {
if (new_skipButton.classList[1] === "new") {
new_skipButton.innerText = "Skip";
new_skipButton.classList.remove("new");
new_skipButton.classList.add("skip");
socket.emit("videoChat", true);
strangerVideo.poster="/res/gifs/spinner.gif";
socket.connect();
} else {
if (new_skipButton.classList[1] === "skip") {
  new_skipButton.innerText = "New";
  new_skipButton.classList.remove("skip");
  new_skipButton.classList.add("new");
  socket.emit("videoChat", false);
  addVideoStream(strangerVideo, null);
  strangerVideo.poster=null;
  socket.disconnect();
}
}
});

// send button enable/stranger connected
socket.on("strangerConnection", (condition) => {
// console.log("i'm condition ", condition);
if (condition) {
socket.emit("connectionReq", true);
if( navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true,
        })){

          navigator.mediaDevices.getUserMedia({
          video: true,
          audio: true,
        }).then((stream) => {
            // added our video to the screen
          addVideoStream(strangerVideo, stream);
    
});

}
}
});

// stranger disconnects
socket.on("disconnectedUser", (condition) => {
// console.log("Someone Disconnected");
if (condition) {
 location.reload();
  new_skipButton.innerText = "New";
  new_skipButton.classList.remove("skip");
  new_skipButton.classList.add("new");
  socket.disconnect();
}
});



// let mediaSource = new MediaSource();
// strangerVideo.src = URL.createObjectURL(mediaSource);

// // Event listener for the sourceopen event
// mediaSource.addEventListener('sourceopen', function() {
  
//     // Event listener for receiving incoming stream data
//     socket.on("strangerStream", function(streamData) {
//         try {
          
//             // Check if the MediaSource is in the 'open' stat
//             if (mediaSource.readyState === 'open') {
//                 // Create a new SourceBuffer for each stream
//                 const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
                
//                 // Append the received data to the source buffer
//                 sourceBuffer.appendBuffer(streamData);
//             } else {
//                 console.warn('MediaSource is not in the "open" state.');
//             }
//         } catch (error) {
//             console.error('Error appending buffer:', error);
//         }
//     });
// });

// // Event listener for the error event
// mediaSource.addEventListener('error', function(event) {
//     console.error('MediaSource error:', event);
// });


//  adding stranger's video to screen
// socket.on("strangerStream", (stream) => {
//   try {
//         // Create a Blob object from the received data
//         const blob = new Blob([stream], { type: 'video/webm' });

//         // Create a URL for the Blob object
//         const videoURL = URL.createObjectURL(blob);

//         // Set the src attribute of the video element to the created URL
//         strangerVideo.src = videoURL;
//     } catch (error) {
//         console.error('Error processing stream data:', error);
//     }
// });
    </script>
  </body>
</html>
