<!DOCTYPE html>
<html>
   <head>
      <title>Chatroom - Lightning Room</title>
      <meta name="description" content="Chat with others in this chatroom!">
      <link rel="stylesheet" href="styles/main.css">
      <link rel="stylesheet" href="styles/room.css">
      <link href="/bootstrap-5.1.3-dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" rel="stylesheet">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
      <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
      <link rel="shortcut icon" type="image/jpg" href="https://media.discordapp.net/attachments/761286162333171734/904834737888198726/unknown.png"/>
      <script 
      <script src="/bootstrap-5.1.3-dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
      <script src="frontend-scripts/notifications.js"></script>
      <script src="https://unpkg.com/showdown@1.9.1/dist/showdown.min.js"></script>
      <script src="js/showdown-target-blank.min.js"></script>
      <script src="frontend-scripts/markdown-eval.js"></script>
            <script defer data-domain="lightningchat.live" src="https://plausible.yeetpc.com/js/plausible.js"></script>
   </head>
   <body>
      <div class="sidenav">
      
         <a href="/" style='font-size: 1em; color: white;'>Global</a>
         <div class="dropdown">
  <a class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" style="font-weight: bold;background-color: #004766;border-color: transparent;"aria-expanded="false">
    Private 
  </a>
  <ul class="dropdown-menu" style="background-color: #004766;border-color: transparent;"aria-labelledby="dropdownMenuButton1">
         <% author.forEach(function (result) { %>
         <% if(result.name == roomname){ %>
         <li> <a class="dropdown-item" href=<%="/room?name="+encodeURIComponent(result.name)%> style='font-size: 1em; color: black;'><%= result.name%></a></li>
         <% }else{ %>
          <li><a class="dropdown-item" href=<%="/room?name="+encodeURIComponent(result.name)%> style='font-size: 1em; color: white;'><%= result.name%></a></li>
         <% } %> 
         <% }) %>
         <% other.forEach(function (result) { %>
         <% if(result.name == roomname){ %>
          <li><a class="dropdown-item" href=<%="/room?name="+encodeURIComponent(result.name)%> style='font-size: 1em; color: black;'><%= result.name%></a></li>
         <% }else{ %>
          <li><a class="dropdown-item" href=<%="/room?name="+encodeURIComponent(result.name)%> style='font-size: 1em; color: white;'><%= result.name%></a></li>
         <% } %> 
         <% }) %>
         </ul>
</div>
<div class="dropdown">
  <a class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" style="font-weight: bold;background-color: #004766;border-color: transparent;"aria-expanded="false">
    Public 
  </a>
  <ul class="dropdown-menu" style="background-color: #004766;border-color: transparent;"aria-labelledby="dropdownMenuButton1">
         <% publicrooms.forEach(function (result) { %>
         <li> <a class="dropdown-item" href=<%="/room?name="+encodeURIComponent(result.name)%> style='font-size: 1em; color: white; '><%= result.name%></a></li>
         <% }) %>
         </ul>
</div>
      </div>
      <nav class="navbar navbar-expand-lg fixed-top navbar-dark" style='background-color:#004766; margin-bottom: 20%;'>
         <div class="container-fluid">
            <a style="color: #ffd166;"class="navbar-brand" href="/">Lightning âš¡</a>
            <button id="enable" type="button" class="btn btn-warning" onclick="askNotificationPermission()">Enable Notifications</button>
            <script>
               notificationBtn = document.getElementById("enable");
               
               if(Notification.permission === 'denied' || Notification.permission === 'default') {
               notificationBtn.style.display = 'block';
               } else {
               notificationBtn.style.display = 'none';
               }
            </script>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
               <% if(loggedin == true){ %>
               <h5 class="nav-item dropdown">
               <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" style='color: #b7b7b7;'aria-expanded="false">
               <%=name1%>
               </a>
               <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                  <li><a class="dropdown-item" href="/account">Account</a></li>
                  <li><a class="dropdown-item" href="/chatrooms">Chatrooms</a></li>
                  <li><a class="dropdown-item" href="/newchatroom">New Chatroom</a></li>
                  <li><a class="dropdown-item" href="/help">Help</a></li>
                  <% if(item[0].type == 'Mod'){ %>
                  <% } %>
                  <li><a class="dropdown-item" href="/logout">Logout</a></li>
               </ul>
               </li>
               <% }else{ %>
               <form class="d-flex">
                  <a class="btn btn-outline-success" style = 'margin-right: 5%;'href='/login'>Login</a>
               </form>
               <% } %>
            </div>
         </div>
      </nav>
      <script>
         function edit(id){
         const firstchildEl = document.getElementById(id+'hi')
         firstchildEl.type = 'text'
         const text = document.getElementById(id)
         firstchildEl.value = text.innerHTML
         text.style.visibility = 'hidden';
         
         const last = document.getElementById(id+'button')
         last.style.visibility = 'visible'
         
         
         }
         function reply(id){
         const firstchildEl = document.getElementById(id+'reply')
         firstchildEl.type = 'text'
         
         const last = document.getElementById(id+'replybutton')
         last.style.visibility = 'visible'
         
         
         }
      </script>
      <script>
         var count = 0;
            
      </script>   
      <% var count = 0 %>
      <div class="chatroom-messages">
         <% item.forEach(function (result) { %>
         <% count++ %>
         <% if(count == 1){ %>
         <div class="card" id='first' style="width: 100%;float:right;">
            <div class="card-body" style = 'text-align:left;' id = "<%= result.id%>parent">
               <p id=<%= count%>><img class="pfp" src=<%="/pfps/"+ result.user+".jpg" %> onerror="this.src='/pfps/originalpfp.jpg';"><strong style="color: #b7b7b7;display: inline-block;"><%=result.user %></strong>: <span class="toConvert"><%= result.text %></span></p>
            </div>
         </div>
         </ul>
         <% }else{ %>
         <div class="card" style="width: 100%;float:right;">
            <div class="card-body" style = 'text-align:left;' id = "<%= result.id%>parent">
               <p id=<%= count%>><img class="pfp" src=<%="/pfps/"+ result.user+".jpg" %> onerror="this.src='/pfps/originalpfp.jpg';"> <strong style="color: #b7b7b7;"><%= result.user %></strong>: <span class="toConvert"><%= result.text %></span></p>
            </div>
         </div>
         </ul>
         <% } %>
         <script>
            count++
            var d = new Date(<%= result.timenumber %>);
            
            var localTime = d.getTime()
            var localOffset = d.getTimezoneOffset() * 60000;
            var utc = localTime + localOffset;
             var offset = new Date().getTimezoneOffset(), o = Math.abs(offset);
            offset = (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + "." + ("00" + (o % 60)).slice(-2)
            var finalDate = new Date(utc + (3600000*offset)).toLocaleString()
            
            document.getElementById(count).title = finalDate
                    evalMarkdown(count)
            
         </script>
         <%})%>
         <div id='messages'>
         </div>
      </div>
      <div class="typing"></div>
      </div>
      <form name="form" id='form' >
         <div>
         </div>
         <script src="https://kit.fontawesome.com/ce3c8c944f.js" crossorigin="anonymous"></script>
         <input name = 'name' id = 'name' style="font-family:sans-serif;font-size:1em;"type='hidden' value = <%=name1%> required />
         <% var date = new Date().getTime().toString()%>
         <input type="hidden" id = 'date' name = 'date'value="<%=date%>">  
         <input name = 'roomname' id = 'roomname' style="font-family:sans-serif;font-size:1em;"type='hidden' value = "<%=roomname%>" required />
         <input type="hidden" id = 'author' name = 'author'value="<%=name1%>">  
         <br>
         <br>
         <button style="display:none"id = 't'type="submit" value="Submit" class='btn btn-success'></button>
      </form>
      <script>
         function imageSend(){
           var socket = io()
         
          let uri = $("#image").val().split('?')[0];
             //moving on, split the uri into parts that had dots before them
             var parts = uri.split('.');
             //get the last part ( should be the extension )
             var extension = parts[parts.length-1];
             //define some image types to test against
             var imageTypes = ['jpg','jpeg','tiff','png','gif','bmp'];
             //check if the extension matches anything in the list.
                 if(imageTypes.indexOf(extension) !== -1) {
         
         socket.emit('chatroom message', '<a href="' + $("#image").val() + '">' + '<img class="chat-image" src="' + $("#image").val() + '"></a>', $('#name').val(), $('#roomname').val(),  $('#date').val());
         $("#comment").val(' ');
         return false;
         }
         else{
         alert("That is an invalid image!")
         $("#comment").val(' ');
         }
         }
         
      </script>
   <div class="card"><a title="Upload an image or gif" data-bs-toggle="modal" data-bs-data-bs-toggle="modal" data-bs-target='#modalforimage'><span id="images"><i class="far fa-image"></i></span></a></div>
      <div class="modal fade" id='modalforimage' tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
         <div class="modal-dialog">
            <div class="modal-content">
               <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Send Image Address Link:</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
               </div>
               <form id="form_id" name="myform">
                  <div class="modal-body">
                     <input type='text' name='image' id='image' size="50"></input>
                  </div>
                  <div class="modal-footer">
                     <button type="submit" onclick='imageSend()'class="btn btn-primary" data-bs-dismiss="modal" >Send</button>
                  </div>
               </form>
            </div>
         </div>
      </div>
      <div class="input-container">
         <textarea name="comment" id="comment" required></textarea>
      </div>
      <div class="buffer">
         <p>buffer</p>
      </div>
      <script>
         $('html,body').animate({scrollTop: document.body.scrollHeight},"slow");
         
         // Get the input field
         var input = document.getElementById("comment");
         
         // Execute a function when the user releases a key on the keyboard
         input.addEventListener("keyup", function(event) {
           // Number 13 is the "Enter" key on the keyboard
           if (event.keyCode === 13  && !event.shiftKey) {
             // Cancel the default action, if needed
             event.preventDefault();
             // Trigger the button element with a click
             document.getElementById("t").click();
           }
         });
         
      </script>
      <script>
         async function addMessages(message){
          <% count++ %>
         count++
         var d = new Date(parseInt(message.date));
         
         var localTime = d.getTime()
         var localOffset = d.getTimezoneOffset() * 60000;
         var utc = localTime + localOffset;
         var offset = new Date().getTimezoneOffset(), o = Math.abs(offset);
         offset = (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + "." + ("00" + (o % 60)).slice(-2)
         var finalDate = new Date(utc + (3600000*offset)).toLocaleString()
         createNotification(message.user);
         
          message.text = message.text.replace(/<\/?p[^>]*>/g,"")
         $("#messages").append(`
           <div class="card" style="width: 100%;float:right;">
         <div class="card-body" style = 'text-align:left;color:"#731768"'>
         
          <p id=${count} title="${finalDate}"><img class="pfp" src="/pfps/${message.user}.jpg" onerror="this.src='/pfps/originalpfp.jpg';"><strong style="color: #b7b7b7;display: inline-block;">${message.user}</strong>: <span class="toConvert">${message.text}</span></p>   
         </div>
          `)
            if(!message.text.startsWith('<a')){
            evalMarkdown(count)
         }
         
         $('html,body').animate({scrollTop: document.body.scrollHeight},"slow");
         
         }  
      </script>
      <script src="/socket.io/socket.io.js"></script>
      <script>
         $(function (){
         var socket = io()
         var typing=false;
         var timeout=undefined;
         var user;
         $(document).ready(function(){
               $('#comment').keypress((e)=>{
                 if(e.which!=13){
                   typing=true
                   socket.emit('typing', {user:$('#name').val(), typing:true, chatroom: $('#roomname').val()})
                   clearTimeout(timeout)
                   timeout=setTimeout(typingTimeout, 3000)
                 }else{
                   clearTimeout(timeout)
                   typingTimeout()
                   //sendMessage() function will be called once the user hits enter
                 }
               })
         
               //code explained later
               socket.on('display', (data)=>{
                 if(data.typing==true && data.chatroom == $('#roomname').val())
                   $('.typing').text(`${data.user} is typing...`)
                 else
                   $('.typing').text("")
               })
          })
         $('form').submit(function(){
         socket.emit('chatroom message', $('#comment').val().replace(/<\/?script[^>]*>/g,""), $('#name').val(), $('#roomname').val(), $('#date').val());
         $("#comment").val('');
         return false;
         })
         });
      </script>
      <script>
         var socket = io();
         
         socket.on('chatroommessage', addMessages)
          function typingTimeout(){
         typing=false
         socket.emit('typing', {user:$('#name').val(), typing:false, chatroom: $('#roomname').val()})
         }
      </script>   
   </body>
</html>