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

<script lang="ts">
import Loading from "../../shared/components/Loading/Loading.vue";
import CallManager, { ECallEvents } from "../ws/call.manager";
import WebsocketService from "../ws/websocket.service";
import VideoStrip from "./call_views/VideoStrip.vue";
import Services from "../../services/index";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    Loading,
    VideoStrip
  },
  name: "Call",
  async created() {
    this.loading = true;
    try {
      const callId = Number(this.$route.params.id);
      const ws = await WebsocketService.getInstance();
      this.callManager = ws.callManager;
      this.callManager.on(ECallEvents.CLOSE, this.endCall);

      const success = await this.callManager.connectToCall(
        this.user.id,
        {
          video: true,
          audio: true
        },
        callId
      );
      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.callStarted();
      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.callEnded();
    return true;
  },
  methods: {
    async setupCall(): Promise<boolean> {
      return true;
    },
    endCall(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", "callStarted", "callEnded"])
  },
  computed: {
    ...mapGetters(["user", "inCall"])
  },
  watch: {
    $route(to, from) {
      const toDepth = to.path.split("/").length;
      const fromDepth = from.path.split("/").length;
      this.stateTransitionName =
        toDepth < fromDepth ? "slide-right" : "slide-left";
    }
  },
  data() {
    return {
      loading: true,
      localStream: null,
      remoteStream: null,
      callManager: null as CallManager,
      stateTransitionName: "slide-left"
    };
  },
  beforeCreate: () => {}
};
</script>


