<template>
  <div>
    <b-button-group class="mt-lg-3">
      <b-button @click="pingServer()" variant="warning" size="sm">Ping Server</b-button>
      <b-button @click="logOn()" variant="success" size="lg">LogOn</b-button>
      <b-button @click="logOff()" size="lg">LogOff</b-button>
    </b-button-group>
    <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>
      <b-list-group horizontal="">
        <b-list-group-item v-for="m in socketMessages.slice(-8)" :key="m + ''">
          {{ m.data.state }}
          <div v-if="m.data.extras">Extras: {{ m.data.extras }}</div>
        </b-list-group-item>
      </b-list-group>
      <ul id="messages">
      </ul>
    </div>
  </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(message) {
      message = { data: JSON.parse(message), received: new Date().toISOString() };
      console.log("S.mC| Message augmented:", message);
      this.socketMessages.push(message);
      this.$store.commit("message", message);
      this.$emit("message", message);
    }
  },

  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.socketMessages = [];
    }
  }
};
</script>
<style>
.list-group-item {
  font-size: small;
}
</style>