<template>
  <div class="wrapper">
    <div v-if="loading">
      <Loading />
    </div>
    <div v-else class>
      <div class="floating-host is-flex" style="position:fixed;top:60px;left:100px">
        <h1 class="subtitle m-r-md">Host:</h1>
        <div class="me">
          <figure class="image is-24x24">
            <img
              :src="isHost? user.avatar : callManager.peer.avatar"
              class="is-rounded is-avatar"
              @click="changeHost()"
            />
          </figure>
        </div>
      </div>
      <div class="video-strip m-b-md is-outlined">
        <video
          :src-object.prop.camel="localStream"
          autoplay
          playsinline
          muted="true"
          style="max-width:20%"
        />
        <video :src-object.prop.camel="remoteStream" autoplay style="max-width:20%" />
      </div>
      <div class="is-flex">
        <div class="go-left m-r-sm" style="display: flex; align-items: center;">
          <button class="button is-outlined" :disabled="!isHost" @click="onLeftClicked()">
            <i class="fa fa-fw fa-arrow-left"></i>
          </button>
        </div>
        <flipbook
          class="flipbook"
          :pages="createPages(book)"
          forwardDirection="left"
          :zooms="null"
          :enabled="isHost"
          @flip-left-end="onFlip('left')"
          @flip-right-end="onFlip('right')"
          ref="flipbook"
          v-slot="flipbook"
        >
          <div class="page-progress has-text-centered m-b-none">
            <p>Page {{ flipbook.page }} of {{ flipbook.numPages }}</p>
          </div>
        </flipbook>
        <div class="go-right m-l-sm" style="display: flex; align-items: center;">
          <button class="button is-outlined" :disabled="!isHost" @click="onRightClicked()">
            <i class="fa fa-fw fa-arrow-right"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Loading from "../../shared/components/Loading/Loading.vue";
import WebsocketService from "../scripts/websocket.service";
import CallManager, { ECallEvents } from "../classes/call.manager";
import Flipbook from "../components/flipbook/flipbook.cjs.js";
import Services from "../../services/index";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    Loading,
    Flipbook
  },
  name: "Call",
  mounted() {
    const self = this;
    setTimeout(() => {
      self.isMounted = true;
    }, 1000);
  },
  async created() {
    this.loading = true;
    try {
      const callId = Number(this.$route.params.id);
      const ws = await WebsocketService.getInstance();
      this.callManager = new CallManager(ws, callId, this.user.id);
      this.callManager.on(ECallEvents.CLOSE, this.callEnded);
      this.callManager.on(ECallEvents.ACTION_BOOK_FLIP, this.onRemoteFlip);
      const success = await this.callManager.connectToCall({
        video: true,
        audio: true
      });
      this.callManager.on(
        ECallEvents.CALL_HOST_CHANGED,
        this.onRemoteHostChanged
      );
      if (!success) {
        this.notify({ message: "Can find this call...", level: "danger" });
        this.$router.push({ path: `/` });
        return false;
      }
      this.localStream = await this.callManager.getUserMedia();
      this.remoteStream = this.callManager.getRemoteStream();
      this.notify({ message: "Connected!", level: "success" });
    } catch (e) {
      console.error(e);
      this.notify({ message: e.message, level: "danger" });
    }

    this.loading = false;
  },
  async beforeDestroy() {
    console.log("destroyed");
    this.callManager.close();
    return true;
  },
  methods: {
    async setupCall(): Promise<boolean> {
      return true;
    },
    onFlip(direction: "left" | "right") {
      if (this.isHost)
        this.callManager.send(`book:action:flip-page`, { direction });
    },
    onLeftClicked() {
      this.$refs.flipbook.flipLeft();
    },
    onRightClicked() {
      this.$refs.flipbook.flipRight();
    },
    onRemoteFlip(payload) {
      switch (payload.direction) {
        case "left":
          this.$refs.flipbook.flipLeft();
          break;
        case "right":
          this.$refs.flipbook.flipRight();
          break;
      }
    },
    createPages(book) {
      const pages = [null];
      for (let i = 1; i < book.pages + 1; i++) {
        pages.push(`/u/images/${i}.JPG`);
      }
      return pages;
    },
    callEnded(callId) {
      this.notify({ message: `Call #${callId} Ended` });
      this.$router.push({ path: `/` });
    },
    onRemoteHostChanged(payload) {
      console.log("-----------");
      console.log(payload);
      this.peer = this.callManager.peer;
      this.isHost = this.callManager.isHost;
    },
    changeHost() {
      this.callManager.changeHost();
    },
    ...mapActions(["notify"])
  },
  computed: {
    ...mapGetters(["user"])
  },
  data() {
    return {
      book: {
        title: "Taylor",
        pages: 34
      },
      loading: true,
      localStream: null,
      remoteStream: null,
      callManager: null,
      isHost: false,
      // currentPage: 0,
      // totalPages: 34,
      isMounted: false
    };
  },
  beforeCreate: () => {}
};
</script>


