<template>
    <div>
        <p v-if="isConnected">We're connected to the server!</p>
        <p v-if="!isConnected">We're not connected yet...</p>

        <div v-if="socketMessages.length >= 1">
            <p>Messages from server"</p>
            <ul id="messages">
                <li v-for="message in socketMessages.slice(-20)" :key="message">
                    {{ message }}
                </li>
            </ul>
        </div>

        <button @click="pingServer()">Ping Server</button>
        <button @click="logOn()">LogOn</button>
        <button @click="logOff()">LogOff</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                isConnected: false,
                socketMessages: []
            }
        },

        sockets: {
            connect() {
                // Fired when the socket connects.
                this.isConnected = true;
                console.log("login");
            },
            disconnect() {
                this.isConnected = false;
                console.log("logoff");
                this.socketMessages = [];
            },
            // Fired when the server sends something on the "messageChannel" channel.
            messageChannel(data) {
                this.socketMessages.push(data);
                console.log("Message received:", data, "!");
            }
        },

        methods: {
            pingServer() {
                // Send the "pingServer" event to the server.
                if (this.isConnected) {
                    this.sendMessage("Ping!");
                    console.log("Ping sent!");
                }
            },
            sendMessage(message) {
                this.$socket.emit('pingServer', message);
                console.log("Message sent:", message);

            },
            logOn() {
                this.$socket.onconnect();
            },
            logOff() {
                this.$socket.ondisconnect();
                this.socketMessage = [];
            }
        }
    }
</script>