var socket;
var username = "";

function addMessage(author, message) {
    var li = document.createElement("li");
    li.innerHTML = "<b>" + author + ": </b>";
    li.innerText += message;
    document.getElementById("messages").appendChild(li);
    document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}

function sendMessage() {
    socket.emit("message",  {message: document.getElementById("message-input").value});
    document.getElementById("message-input").value = "";
}


document.addEventListener("DOMContentLoaded", () => {

    try {
        socket = io("https://danby.aniere.fr:3000");

        socket.on("update-count", (data) => {
            document.getElementById("value").innerText = data.value;
        });

        socket.on("username", (data) => {
            username = data.username;
        });

        socket.on("new-message", (data) => {
            addMessage(data.author, data.message);
        });

        socket.on("warning", () => {
            addMessage("Rappel", "Vous devez parler uniquement de denis !");
        });


    } catch(error) {
        document.getElementById("value").innerText = "Serveur injoingnable !";
    }
    
});

const swiper = new Swiper('.swiper', {
    direction: "horizontal",
    loop: true,
    autoplay: true,
    speed: 400,
    spaceBetween: 100,
});


document.getElementById("chat-button").addEventListener("click", () => {
    document.getElementById("chat").style.display = "block";
});

document.getElementById("close").addEventListener("click", () => {
    document.getElementById("chat").style.display = "none";
});

document.getElementById("send").addEventListener("click", sendMessage);

document.getElementById("message-input").addEventListener("keyup", (event) => {

    if(event.key == "Enter") {
        sendMessage();
    }
});


const addMaximumScaleToMetaViewport = () => {
    const el = document.querySelector('meta[name=viewport]');
  
    if (el !== null) {
      let content = el.getAttribute('content');
      let re = /maximum\-scale=[0-9\.]+/g;
  
      if (re.test(content)) {
          content = content.replace(re, 'maximum-scale=1.0');
      } else {
          content = [content, 'maximum-scale=1.0'].join(', ')
      }
  
      el.setAttribute('content', content);
    }
  };
  
  const disableIosTextFieldZoom = addMaximumScaleToMetaViewport;
  
  // https://stackoverflow.com/questions/9038625/detect-if-device-is-ios/9039885#9039885
  const checkIsIOS = () =>
    /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  
  if (checkIsIOS()) {
    disableIosTextFieldZoom();
  }