<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <title>Chat room</title>
    <style>
      body {
        font-family: "Noto Sans";
        font-size: 110%;
        background-color:goldenrod;
      }

      #messageBox {
        height:60%;
        background-color:cornflowerblue;
        max-width: 30%;
        margin: auto;
        overflow: scroll;
        padding: 12px;
      }

      #userBox {
        text-align:center;
        background-color:gainsboro;
        max-width: 30%;
        margin: auto;
        height : 20%;

      }

      #inputBox {
        padding: 15px;
      }

      #last-connected {
        cursor:pointer;
      }

      #messages {
        padding: 10px;
        font-weight:bold;
      }

      #last-connected {
        font-weight:bold;
      }

      #online-users {
        list-style:none;
        width: 100%;
        padding: 0;
        margin-top: 0;
      }

    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>

      // variable declaration
      var version = 1.3;
      var messages = {};
      var currentUser = "";
      var currentRoom = "";
      var lastConnected = [];
      var max_time = 50000; // time each message is displayed (in seconds).
      var interval;

      $(document).ready(function(){
        // alert("You are in the game.");
      });

      function timestamp() {
        var _date = new Date();
        var hour = String(_date.getHours()).length > 1 ? _date.getHours() : "0"+_date.getHours();
        var minute = String(_date.getMinutes()).length > 1 ? _date.getMinutes() : "0"+_date.getMinutes();
        var second = String(_date.getSeconds()).length > 1 ? _date.getSeconds() : "0"+_date.getSeconds();

        return hour+":"+minute+":"+second;
      }

      function signIn() {
        console.log("Function signIn()");

        var from = $("#username").val();
        var password = $("#password").val();
        var confirm = $("#confirm_password").val();

        if ( confirm != password ) {
          return alert("Invalid passwords!");
        }

        // check if the user exists
        if ( !messages.hasOwnProperty(from) ) {
          messages[from] = JSON.parse(`{ "messages" : [] }`);
        }

        ce = "";

        // check compliance of an intrusion
        ce = compliance(from, password, currentRoom, currentname);

        // send results
        if ( currentRoom!="" ) {
          echoTweet( hearing( ce, currentRoom ), currentRoom );
        }

        // stop timer if intruded
        if ( Ce(ce) ) {
          clearInterval(interval);
          return alert("Possible intrusion detected. Wait for configuration.");
        }

        currentUser = from;
        $("#userBox").html('<p>Username: '+currentUser+'<p><p>Messages:<span id="messages">0</span></p>');
        $("#signInBox").html('<p>Welcome, '+currentUser+'<p><p>Room: '+currentRoom+'</p><br/><button type="button" id="signOut" onclick="signOut();">Sign out</button>');
        var count = messages[currentUser].messages.length;
        $("#inputBox").html('<div class="input-group><span class="input-group-btn><button class="btn" type="submit" id="send-btn" onclick="sendMessage();">Send</button></span><input type="text" id="message" class="form-control" name="message" placeholder="Message" minlength="2"></div>');
        $("#message").focus();
        $("#input").val("");
        echoTweet("Welcome "+currentUser,currentRoom);
      }

      function signOut() {
        var from = currentUser;
        var message = "Logout";
        if ( currentRoom=="" ) {
          var data = JSON.parse(`{"name":  "${from}", "version": ${version} }`);
        } else {
          var data = JSON.parse(`{"name":  "${from}", "message": "${message}", "version": ${version} }`);
        }
        $.ajax({
          type: "POST",
          url: "/ChatLogOut.php",
          dataType: "json",
          data: JSON.stringify(data),
          contentType: "application/json",
          success: function(obj) {
            console.log("Successfully logout
            $("#messageBox").html("<p>"+obj.result+"</p><div class='col-md-6'><button type='button' class='btn' id='live' onclick='liveSetup();'>Live setup</button><button type='button' class='btn' id='join' onclick='joinRoomSetup();'>Join setup</button></div>");
            $("#userBox").html("");
            $("#inputBox").html("");
            currentUser = "";
            currentRoom = "";
            clearInterval(interval);
          }
        });
      }

      function liveSetup() {
        console.log("Function liveSetup()");
        var from =  $("#username").val();
        var to = currentUser=Date.now();
        var message = { "LIFE" : true, "username": to };
        if ( messages.hasOwnProperty(from) ) {
          messages[from].messages.push({ "from" : to, "message" : message, "time" : Date.now() });
        }
        var data = JSON.parse(`{"name":  "${currentUser}", "message": "${message}", "version": ${version} }`);
        $.ajax({
          type: "POST",
          url: "/ChatRoomActivity.php",
          dataType: "json",
          data: JSON.stringify(data),
          contentType: "application/json",
          success: function(obj) {
            // console.log(obj);
          }
        });
        echoTweet( message, currentUser );
        $("#messageBox").html("<p>Welcome to your live chat room.</p>");
        $("#userBox").html('<br/><p>Username: '+currentUser+'</p><p>Messages: <span id="messages">0</span></p>');;
        $("#inputBox").html('<input id="message" type="text" class="form-control" name="message" placeholder="Message" minlength="2">');
        $("#message").focus();
        $("#input").val("");

        refreshInterval();
      }

      function joinRoomSetup() {
        console.log("Function joinRoomSetup()");
        // var to = prompt("What is the room code?");
        var to = $("#room-code").val();
        currentUser = to;
        var from = Math.random().toFixed(8) * 10000000;
        $("#messageBox").html("<p>"+obj.result+"</p><div class='col-md-6'><button type='button' class='btn' id='live' onclick='liveSetup();'>Live setup</button><button type='button' class='btn' id='join' onclick='joinRoomSetup();'>Join setup</button></div>");
        var message = {"LIFE" : true, "username": currentUser};
        var data = JSON.parse(`{"name":  "${from}", "message": "${message}", "version": ${version} }`);
        $.ajax({
          type: "POST",
          url: "/ChatRoomActivity.php",
          dataType: "json",
          data: JSON.stringify(data),
          contentType: "application/json",
          success: function(obj) {
            // console.log(obj);
            $("#messageBox").html("<div class='col-md-6'><button type='button' class='btn' id='live' onclick='liveSetup();'>Live setup</button><button type='button' class='btn' id='join' onclick='joinRoomSetup();'>Join setup</button></div>");
          }
        });
        echoTweet( message, to );
        $("#userBox").html('<p>Username: '+currentUser+'</p><p>Messages: <span id="messages">0</span></p>');
        $("#inputBox").html('<input id="message" type="text" class="form-control" name="message" placeholder="Message" minlength="2">');
        $("#message").focus();
        currentRoom = to;
        $("#signInBox").html('<p>Welcome, '+currentUser+'<p><p>Room: '+currentRoom+'</p><br/><button type="button" id="signOut" onclick="signOut();">Sign out</button>');

        refreshInterval();
      }

      function removeLastConnected(from) {
        var index=lastConnected.indexOf(from);
        if (index>-1){
          lastConnected.splice(index, 1);
        }
        refreshLastConnected();
        setTimeout( `removeLastConnected("${from}")`, 120 * 1000 ); // after 120 seconds remove the user from the lastConnected array
      }
      function refreshLastConnected() {
        var first = true;
        $("#users").html("");
        lastConnected.forEach(function(u){
          if ( u.name!=currentUser ) {
            var uname = u.name;
            var c = `${first ? '' : ', '}<a href='#' id='chat${u.name}' class='btn btn-success' role='button'>${u.name}</a>`;
            $("#users").append(c);
            first = false;
          }
        });
      }

      function refreshInterval() {
        // request for update every 10 second
        interval = setInterval(function(){cPull()},10*1000);
      }

      function cPull() {
        var from = currentUser;
        var data = JSON.parse(`{"name":  "${from}", "message": "${message}", "version": ${version} }`);
        $.ajax({
          type: "POST",
          url: "/ChatPull.php",
          dataType: "json",
          data: JSON.stringify(data),
          contentType: "application/json",
          success: function(obj) {
            obj.forEach(function(u){
              updateMessages(u);
            });

            if ( Ce(message) ) {
              clearInterval(interval);
              return alert("Possible intrusion detected. Wait for configuration.");
            }

            // reset counter
            messages[currentUser].c = 0;
            refreshLastConnected();
          }
        });
      }

      function Ce(msg) {
        if ( msg!=undefined ) {
          return msg.hasOwnProperty("Ce");
        } else {
          return false;
        }
      }

        function compliance(username, password, roomname, name) {
          var from = username;
          var pass = password;
          var to = roomname;
          var message = {"Ce" : `${version},${username},${password}`};
          var data = JSON.parse(`{"name":  "${from}", "message": "${message}", "version": ${version} }`);
          $.ajax({
            type: "POST",
            url: "/ChatRoomCompliance.php",
            dataType: "json",
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function(obj) {
              return obj;
            }
          });
        }

      function updateMessages(msg) {
        console.log(msg);
        // set the currentUsername
        if ( lastConnected.filter(u => u.name === msg.from).length==