<template>
  <div class="is-fullwidth">
    <div v-if="loading">
      <Loading />
    </div>
    <div v-else class>
      <VideoStrip :localStream="localStream" :remoteStream="remoteStream" />
      <router-view></router-view>
    </div>
  </div>
</template>

<script lang="ts">
import Loading from "../../shared/components/Loading/Loading.vue";
import { ECallEvents } from "../classes/call.manager";
import VideoStrip from "./call_views/VideoStrip.vue";
import Services from "../../services/index";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    Loading,
    VideoStrip
  },
  name: "Call",
  // mounted() {
  //   const self = this;
  //   setTimeout(() => {
  //     self.isMounted = true;
  //   }, 1000);
  // },
  async created() {
    this.loading = true;
    try {
      const callId = Number(this.$route.params.id);

      await this.connectToCall(callId);

      this.callManager.on(ECallEvents.CLOSE, this.callEnded);

      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();
    this.$store.dispatch("callEnded");
    return true;
  },
  methods: {
    async setupCall(): Promise<boolean> {
      return true;
    },
    callEnded(callId) {
      this.notify({ message: `Call #${callId} Ended` });
      this.$router.replace({ path: `/` });
    },
    onRemoteHostChanged(payload) {
      console.log("-----------");
      console.log(payload);
      this.peer = this.callManager.peer;
    },
    changeHost() {
      this.callManager.changeHost();
    },
    ...mapActions(["notify", "connectToCall"])
  },
  computed: {
    ...mapGetters(["user", "callManager", "inCall"])
  },
  data() {
    return {
      loading: true,
      localStream: null,
      remoteStream: null
      // currentPage: 0,
      // totalPages: 34,
      // isMounted: false
    };
  },
  beforeCreate: () => {}
};
</script>


