<template>
  <div class="wrapper">
    <div v-if="loading">
      <Loading />
    </div>
    <div v-else>
      <video
        :srcObject="localStream"
        autoplay="true"
        controls="false"
        playsinline="true"
        muted="true"
      />
      <video :srcObject="remoteStream" autoplay="true" controls="false" />
    </div>
  </div>
</template>

<script lang="ts">
import Loading from "../../shared/components/Loading/Loading.vue";
import WebsocketService from "../scripts/websocket.service";
import Services from "../../services/index";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    Loading
  },
  name: "Call",
  async created() {
    this.loading = true;
    try {
      const ws = await WebsocketService.getInstance();
      const success = await ws.connectToCall(this.$route.params.id);
      if (!success) {
        this.notify({ message: "Can find this call...", level: "danger" });
        this.$router.push({ path: `/` });
        return false;
      }
      this.signalingChannel = this.localStream = await ws.getLocalMedia({
        video: false,
        audio: true
      });
      this.remoteStream = ws.getRemoteStream();
      console.log(this.localStream);
      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");
    const ws = await WebsocketService.getInstance();
    ws.leaveCall();
    return true;
  },
  methods: {
    ...mapActions(["notify"])
  },
  computed: {
    ...mapGetters([])
  },
  data() {
    return {
      loading: true,
      call: null,
      localStream: null,
      remoteStream: null,
      signalingChannel: null
    };
  },
  beforeCreate: () => {}
};
</script>

