<!doctype html>

<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Chat-App - Main Page</title>
    <meta name="description" content="Chat application made for learning and experience purpose. Have fun talking with your friends! Soon more updates and features.">
    <meta name="author" content="RavenStudio">

    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="/css/fontello/css/fontello.css">

    <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=Rubik:ital,wght@0,300;0,400;0,500;0,600;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet"> 
</head>

<body>
    <div class="container">
        <div class="account">
        <% if(typeof username == 'undefined') { %>
            <div class="login-panel">
                <div class="account-manage"><a href="/login">Login</a></div>
                <div style="margin: 5px">|</div>
                <div class="account-manage"><a href="/register">Register</a></div>
            </div>
        <% } else { %>
            <div class="name">Your username: <%=username%></div>
            <div class="btn newroom">Create new room</div>
            <div class="btn"><a href="/logout">Logout</a></div>
        <% } %>
        </div>

        <% if (typeof username != 'undefined') { %>
        <div class="user-interface">
            <div class="panel">
                <div class="panel-header"><div class="header-text">Chat</div><div class="link"><i class="icon-link"></i></div></div>
                <div class="chat"></div>
                <div class="input">
                    <input class="message" type="text" required="true" name="MESSAGE" placeholder="Type something..." />
                    <div class="sendbtn">Send</div>
                </div>
            </div>
            <div class="users">
                <div class="users-wrapper">
                    <div class="users-header"><div class="dot"></div>Online</div>
                    <div class="users-list"></div>
                </div>
            </div>
        </div>
        <% } %>
    </div>

    <% if (typeof username !='undefined' ) { %>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js'></script>
    <script>
        let socket = io()

        let alertCount = 0

        let roomId = `<%=roomId%>`
        window.history.replaceState(null, null, `/<%=method%>/${roomId}`) //Visually change the URL
        let username = `<%=username%>`

        //Join room
        socket.emit('join', { username: username, roomId: roomId })

        let button = document.getElementsByClassName('sendbtn')[0]
        let newRoomButton = document.getElementsByClassName('newroom')[0]
        let message = document.getElementsByClassName('message')[0]
        let copyInvite = document.getElementsByClassName('link')[0]

        let linkAnimation

        //Copy the invite animation
        copyInvite.addEventListener('click', (event) => {
            navigator.clipboard.writeText('https://ravenstudio.ga/join/' + roomId);
            clearTimeout(linkAnimation)
            copyInvite.innerHTML = '<i class="icon-ok"></i>'
            linkAnimation = setTimeout(() => {
            copyInvite.innerHTML = '<i class="icon-link"></i>'
            }, 5000)
        })

        //Send message
        button.addEventListener('click', (event) => {
            SendMessage()
        })

        message.addEventListener('keypress', (event) => {
            if (event.key === "Enter") {
                event.preventDefault()
                SendMessage()
            }
        })

        //Create new room
        newRoomButton.addEventListener('click', (element) => {
            window.location = '/'
        })

        //Update clients list
        socket.on('who', (msg) => {
            let users = document.getElementsByClassName('users-list')[0]

            //Reset the list
            users.innerHTML = ''

            for(let i = 0; i < msg.length; i++)
            {
                let user = document.createElement('div')
                user.className = 'user'

                let userIcon = document.createElement('i')
                userIcon.className = 'icon-user'

                if(msg[i].isHost)
                    userIcon.className = 'icon-crown'

                let usernameText = document.createTextNode(msg[i].username)

                user.appendChild(userIcon)
                user.appendChild(usernameText)
                users.appendChild(user)
            }
        })

        //If we received message we will show it on the screen
        socket.on('message', (msg) => {
            let divMessage = document.createElement('div') //Create message main element
            divMessage.className = 'sent-message'

            let textDiv = document.createElement('div') //Create handler for text
            textDiv.className = 'text-handler'

            let text = document.createTextNode(msg) //Create node for text of the message

            textDiv.appendChild(text)
            divMessage.appendChild(textDiv)

            document.getElementsByClassName('chat')[0].appendChild(divMessage)
            document.getElementsByClassName('sent-message')[document.getElementsByClassName('sent-message').length - 1].scrollIntoView()
        })

        let canWrite = true
        let cooldown

        function SendMessage() {
            if (message.value != "") {
                socket.emit('send', { message: username + ': ' + message.value, roomId: roomId })
                message.value = ''
                alertCount = 0
            }
            else {
                alertCount++
                if (message.value == "" && alertCount >= 4) {
                    alert("Message cannot be empty.")
                    alertCount = 0
                }
            }
        }
    </script>
    <% } %>
</body>

</html>