<template>
  <div class="container">
    <div class="Books">
      <h2 class="subtitle">
        <i class="fa fa-fw fa-book"></i> Select A Book
      </h2>
      <div class="is-flex m-b-md">
        <div
          class="book-thumb m-l-md"
          v-for="(book, index) in callManager.books"
          :key="index"
          @click="goToBook(book, index, false)"
          :disabled="!callManager.isHost"
        >
          <div class="book-cover">
            <figure class="image is-2by3 m-a">
              <img :src="`/u/books/${book.id}/thumbnail`" />
            </figure>
          </div>
          <div class="book-text">
            <div>{{book.title}}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { mapGetters } from "vuex";
import { ECallEvents } from "../../ws/call.manager";
import WebsocketService from "../../ws/websocket.service";
export default {
  name: "CallLobby",
  async created() {
    const ws = await WebsocketService.getInstance();
    this.callManager = ws.callManager;
    this.callManager.on(
      ECallEvents.CALL_VIEW_BOOK,
      this.remoteBookSelected.bind(this)
    );
  },
  data() {
    return {
      callManager: { books: [] }
    };
  },
  methods: {
    goToBook(book, index, remote) {
      if (remote || this.callManager.isHost) {
        this.callManager.selectBook(index, remote);
        this.$router.replace({ name: "book" });
      }
    },
    remoteBookSelected({ bookId }) {
      for (let index = 0; index < this.callManager.books.length; index++) {
        const book = this.callManager.books[index];
        if (book.id === bookId) {
          this.goToBook(book, index, true);
          return;
        }
      }
    }
  },
  computed: {
    ...mapGetters(["user"])
  }
};
</script>
