<template>
  <div class="wrapper">
    <div v-if="loading">
      <Loading />
    </div>
    <div v-else class="is-flex">
      <video
        :srcObject="localStream"
        autoplay="true"
        controls="false"
        playsinline="true"
        muted="true"
        style="max-width:40%"
      />
      <video :srcObject="remoteStream" autoplay="true" controls="false" style="max-width:40%" />
    </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 Services from "../../services/index";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    Loading
  },
  name: "Call",
  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.callManager.on(ECallEvents.CLOSE, this.callEnded);
      const success = await this.callManager.connectToCall({
        video: true,
        audio: true
      });
      if (!success) {
        this.notify({ message: "Can find this call...", level: "danger" });
        this.$router.push({ path: `/` });
        return false;
      }
      this.localStream = this.callManager.getUserMedia({
        video: true,
        audio: true
      });
      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;
    },
    callEnded(callId) {
      this.notify({ message: `Call #${callId} Ended` });
      this.$router.push({ path: `/` });
    },
    ...mapActions(["notify"])
  },
  computed: {
    ...mapGetters([])
  },
  data() {
    return {
      loading: true,
      localStream: new MediaStream(),
      remoteStream: new MediaStream(),
      callManager: null
    };
  },
  beforeCreate: () => {}
};
</script>

