<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/public/styles.css">
    <script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/peerjs/1.3.1/peerjs.min.js.map"></script>
    <script src="https://cdn.jsdelivr.net/npm/peerjs@1.3.2/dist/peerjs.min.js"></script>

    <script src="/socket.io/socket.io.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>

    <script>
        const myname = "<%= Myname %>"
        const roomId = "<%= roomid %>"
    </script>
</head>

<body>
    <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Invite People</h4>
                </div>
                <div class="modal-body">
                    <p id="roomid"><strong><%= roomid %></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-white" onclick="cancel()">Close</button>
                    <button type="button" class="btn btn-primary" onclick="copy()">Copy</button>
                </div>
            </div>
        </div>
    </div>
    <div class="mainclone">
        <div class="main_left">
            <div class="main_videos">
                <div id="video-grids">
                </div>
            </div>
            <div class="main_controls">
                <div class="main_controls_block">
                    <div class="main_controls_button" id="mic" onclick="muteUnmute()">
                        <i class="fas fa-microphone-slash"></i>
                        <span>Mute</span>
                    </div>

                    <div class="main_controls_button" id="video" onclick="VideomuteUnmute()">
                        <i class="fas fa-video-slash"></i>
                        <span>Stop Video</span>
                    </div>
                </div>
                <div class="main_controls_block">
                    <div class="main_controls_button" onclick="invitebox()">
                        <i class="fas fa-user-plus"></i>
                        <span>Invite</span>
                    </div>
                    <div class="main_controls_button">
                        <i class="fas fa-user-friends"></i>
                        <span>Participants</span>
                    </div>
                    <div class="main_controls_button" onclick="showchat()">
                        <i class="fas fa-comment-alt"></i>
                        <span>Chat</span>
                    </div>
                </div>
                <div class="main_controls_block">
                    <div class="main_controls_button leave_red">
                        <span class="leave_meeting"><a href="/">Leave Meeting</a></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="main_right" id="chat">
            <div class="main_right_header">
                <h6>Chat Area</h6>
            </div>
            <div class="main__chat_window" id="main__chat_window">
                <ul class="messages" id="messageadd">

                </ul>

            </div>
            <div>
                <div class="main__message_container">
                    <input type="text" id="chat_message" onkeydown="sendmessage(this)" placeholder="Type message here.." />
                </div>
            </div>
        </div>
    </div>
    <!-- <script src="/public/main.js"></script> -->
    <script>
        const socket = io("/");
const main__chat__window = document.getElementById("main__chat_window");
const videoGrids = document.getElementById("video-grids");
const myVideo = document.createElement("video");
const chat = document.getElementById("chat");
OtherUsername = "";
chat.hidden = true;
myVideo.muted = true;

window.onload = () => {
    $(document).ready(function() {
        $("#getCodeModal").modal("show");
    });
};


var peer = new Peer(undefined, {
    path: "/peerjs",
    host: "/",
    port: "",
    config: {
    iceServers: [{'url': 'stun:global.stun.twilio.com:3478', 
    'urls': 'stun:global.stun.twilio.com:3478'},
     {'url': 'turn:global.turn.twilio.com:3478?transport=udp',
      'username': '91757ea8f6d8501acb93c66574a54d7c64c5d7989ad5a8fac17ae413061f84f7', 
      'urls': 'turn:global.turn.twilio.com:3478?transport=udp',
       'credential': '5P3X9Kknwqtgoe8rSteqzOkBQpMlnwOjRW1gXF+7QXc='},
        {'url': 'turn:global.turn.twilio.com:3478?transport=tcp', 
        'username': '91757ea8f6d8501acb93c66574a54d7c64c5d7989ad5a8fac17ae413061f84f7',
        'urls': 'turn:global.turn.twilio.com:3478?transport=tcp', 
        'credential': '5P3X9Kknwqtgoe8rSteqzOkBQpMlnwOjRW1gXF+7QXc='}, 
        {'url': 'turn:global.turn.twilio.com:443?transport=tcp',
         'username': '91757ea8f6d8501acb93c66574a54d7c64c5d7989ad5a8fac17ae413061f84f7',
          'urls': 'turn:global.turn.twilio.com:443?transport=tcp', 
          'credential': '5P3X9Kknwqtgoe8rSteqzOkBQpMlnwOjRW1gXF+7QXc='}]

  }
});

let myVideoStream;
const peers = {};
var getUserMedia =
    navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia;

sendmessage = (text) => {
    if (event.key === "Enter" && text.value != "") {
        socket.emit("messagesend", myname + ' : ' + text.value);
        text.value = "";
        main__chat_window.scrollTop = main__chat_window.scrollHeight;
    }
};

navigator.mediaDevices
    .getUserMedia({
        video: true,
        audio: true,
    })
    .then((stream) => {
        myVideoStream = stream;
        addVideoStream(myVideo, stream, myname);

        socket.on("user-connected", (id, username) => {
            console.log("userid:" + id);
            connectToNewUser(id, stream, username);
            socket.emit("tellName", myname);
        });

        socket.on("user-disconnected", (id) => {
            console.log(peers);
            if (peers[id]) peers[id].close();
        });
    });
peer.on("call", (call) => {
    getUserMedia({ video: true, audio: true },
        function(stream) {
            call.answer(stream); // Answer the call with an A/V stream.
            const video = document.createElement("video");
            call.on("stream", function(remoteStream) {
                addVideoStream(video, remoteStream, OtherUsername);
            });
        },
        function(err) {
            console.log("Failed to get local stream", err);
        }
    );
});

peer.on("open", (id) => {
    socket.emit("join-room", roomId, id, myname);
});

socket.on("createMessage", (message) => {
    var ul = document.getElementById("messageadd");
    var li = document.createElement("li");
    li.className = "message";
    li.appendChild(document.createTextNode(message));
    ul.appendChild(li);
});

socket.on("AddName", (username) => {
    OtherUsername = username;
    console.log(username);
});

const RemoveUnusedDivs = () => {
    //
    alldivs = videoGrids.getElementsByTagName("div");
    for (var i = 0; i < alldivs.length; i++) {
        e = alldivs[i].getElementsByTagName("video").length;
        if (e == 0) {
            alldivs[i].remove();
        }
    }
};

const connectToNewUser = (userId, streams, myname) => {
    const call = peer.call(userId, streams);
    const video = document.createElement("video");
    call.on("stream", (userVideoStream) => {
        //       console.log(userVideoStream);
        addVideoStream(video, userVideoStream, myname);
    });
    call.on("close", () => {
        video.remove();
        RemoveUnusedDivs();
    });
    peers[userId] = call;
};

const cancel = () => {
    $("#getCodeModal").modal("hide");
};

const copy = async() => {
    const roomid = document.getElementById("roomid").innerText;
    await navigator.clipboard.writeText("https://finaltest-v9sp.onrender.com/join/" + roomid);
};
const invitebox = () => {
    $("#getCodeModal").modal("show");
};

const muteUnmute = () => {
    const enabled = myVideoStream.getAudioTracks()[0].enabled;
    if (enabled) {
        myVideoStream.getAudioTracks()[0].enabled = false;
        document.getElementById("mic").style.color = "red";
    } else {
        document.getElementById("mic").style.color = "white";
        myVideoStream.getAudioTracks()[0].enabled = true;
    }
};

const VideomuteUnmute = () => {
    const enabled = myVideoStream.getVideoTracks()[0].enabled;
    console.log(getUserMedia);
    if (enabled) {
        myVideoStream.getVideoTracks()[0].enabled = false;
        document.getElementById("video").style.color = "red";
    } else {
        document.getElementById("video").style.color = "white";
        myVideoStream.getVideoTracks()[0].enabled = true;
    }
};

const showchat = () => {
    if (chat.hidden == false) {
        chat.hidden = true;
    } else {
        chat.hidden = false;
    }
};

const addVideoStream = (videoEl, stream, name) => {
    videoEl.srcObject = stream;
    videoEl.addEventListener("loadedmetadata", () => {
        videoEl.play();
    });
    const h1 = document.createElement("h1");
    const h1name = document.createTextNode(name);
    h1.appendChild(h1name);
    const videoGrid = document.createElement("div");
    videoGrid.classList.add("video-grid");
    videoGrid.appendChild(h1);
    videoGrids.appendChild(videoGrid);
    videoGrid.append(videoEl);
    RemoveUnusedDivs();
    let totalUsers = document.getElementsByTagName("video").length;
    if (totalUsers > 1) {
        for (let index = 0; index < totalUsers; index++) {
            document.getElementsByTagName("video")[index].style.width =
                100 / totalUsers + "%";
        }
    }
};

    </script>
</body>

</html>