<template>
  <div>
    <b-row id="sockets-buttons"  class="m-3">
      <b-col>
        <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>
      </b-col>
    </b-row>
    <b-row id="sockets-status">
      <b-col>
        <p v-if="isConnected">Connecté au serveur</p>
        <p v-if="!isConnected">Déconnecté</p>
      </b-col>
      <b-col>
        <p>
          <b-icon-inbox-fill />
          Messages du serveur: <b v-if="socketMessages.length === 0">Aucun :'(</b>
        </p>
      </b-col>
      <b-row id="sockets-messages">
        <b-card-group deck>
          <b-col
            v-for="m in socketMessages.slice(-8)" :key="JSON.stringify(m)"
          >
            <b-card class="text-center"
                    header-tag="header"
                    v-bind:header="m.data.state"
                    v-bind:sub-title="m.data != null ? m.data.extras != null ? JSON.stringify(m.data.extras) : '' : ''"
            >
            </b-card>
          </b-col>
        </b-card-group>
      </b-row>
      <ul id="messages">
      </ul>
    </b-row>
  </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>