<template>
  <div class="body-color">
    <!-- LOADER -->
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>

    <!-- SNACKBAR -->
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="snackbarColor"
    >
      {{ text }}
      <v-spacer></v-spacer>
      <v-btn flat text @click="snackbar = false">X</v-btn>
    </v-snackbar>

    <v-container grid-list-xl class="pt-0">
      <v-layout row wrap class="mt-1">
        <!-- if logged in user is parent -->
        <v-flex xs12 sm12 md9 v-if=" $store.state.role === 'PARENT' ">
          <v-layout column>
            <!-- HEADING -->
            <v-flex>
              <div
                class="title side-bar-color font-weight-bold"
              >Live Online Classes - {{$route.query.chapterName}}</div>
              <div class="subheading grey--text lighten-1">{{liveLink}}</div>
              <!-- <div
                class="subheading grey--text lighten-1"
              >The session started at 1:00 there is 1 moderator</div>-->
            </v-flex>

            <!-- JOIN OR END SESSION -->
            <v-flex>
              <div>
                <v-btn
                  round
                  class="open-dialog-button"
                  dark
                  v-if="studentBtn"
                  @click="startChat();"
                >{{studentBtn}}</v-btn>
                <span class="subheading grey--twxt lighten-1" v-else>Session hasnt started yet</span>
              </div>
            </v-flex>
            <v-flex id="studentClone">
              <div id="jitsi-container"></div>
            </v-flex>
          </v-layout>
        </v-flex>

        <!-- if logged in user is teacher -->
        <v-flex xs12 sm12 md12 v-else>
          <v-layout column>
            <!-- HEADING -->
            <v-flex>
              <div
                class="title side-bar-color font-weight-bold"
              >Live Online Classes - {{$route.query.chapterName}}</div>
              <!-- <div class="subheading grey--text lighten-1"></div> -->
              <!-- <div
                class="subheading grey--text lighten-1"
              >The session started at 1:00 there is 1 moderator</div>-->
            </v-flex>

            <!-- JOIN OR END SESSION -->
            <v-flex>
              <div>
                <v-btn
                  round
                  class="open-dialog-button"
                  dark
                  @click="startChat()"
                >Start Session</v-btn>
              </div>
            </v-flex>
            <v-flex id="teacherClone">
              <div id="jitsi-container"></div>
            </v-flex>
          </v-layout>
        </v-flex>

        <v-spacer></v-spacer>

        <!-- COURSES SIDE BAR- positioned to the right of the page -->
        <!-- <v-flex xs3>
          <v-card class="elevation-0 card-border" height="100%">
            <CoursesSideBar></CoursesSideBar>
          </v-card>
        </v-flex>-->
      </v-layout>
    </v-container>
  </div>
</template>
<script>
import AllApiCalls from "@/Services/AllApiCalls.js";
import http from "@/Services/http.js";
import moment from "moment";
import Meet from "@/pages/Meet/meet.vue";
import CoursesSideBar from "@/pages/Common/CoursesSideBar.vue";
export default {
  mixins: [AllApiCalls],
  components: {
    CoursesSideBar,
  },
  data() {
    return {
      startLiveSession: "",
      studentBtn: "",

      // DATA TABLE
      search: "",
      pagination: {
        rowsPerPage: 10,
      },
      liveOnlineHeaders: [
        {
          text: "Playback",
          value: "attachementUrl",
          sortable: false,
          align: "center",
        },
        {
          text: "Meeting",
          align: "center",
          sortable: false,
          value: "",
        },
        {
          text: "Recording",
          value: "",
          sortable: false,
          align: "center",
        },
        {
          text: "Description Preview",
          value: "",
          sortable: false,
          align: "center",
        },
        { text: "Date", value: "", sortable: false, align: "center" },
        { text: "Duration", value: "", sortable: false, align: "center" },
        { text: "Toolbar", value: "", sortable: false, align: "center" },
      ],
      liveOnlineItems: [],

      // JITSI CONTAINER
      liveLink: "",
      token: "",
      selectStudents: {},
      classRules: [(v) => !!v || " Class Name is required"],
      sectionRules: [(v) => !!v || " Section Name is required"],
      addclass: [],
      addSection: [],
      loading: false,
      room: "",
      username: "",
      roomPassword: "",
      counter: 0,
    };
  },
  methods: {
    startChat() {
      if (this.$store.state.role === "PARENT") {
        let div = document.getElementById("jitsi-container");
        var parent = div.parentNode;
        var clone = div.cloneNode(true);
        clone.id = "jitsi-container";
        parent.replaceChild(clone, div);
        // div.replaceWith(input.val('').clone(true));
        this.studentClasses();
      }
      if (this.$store.state.role === "TEACHER") {
        let div = document.getElementById("jitsi-container");
        var parent = div.parentNode;
        var clone = div.cloneNode(true);
        clone.id = "jitsi-container";
        parent.replaceChild(clone, div);
        // div.replaceWith(input.val('').clone(true));
        this.createRoom();
      }
    },
    // JITSI CONTAINER
    startConference() {
      console.log("yes session started");
      var _this = this;
      try {
        const domain = "meet.intrack.in";
        const options = {
          audioInput: "<deviceLabel>",
          audioOutput: "<deviceLabel>",
          videoInput: "<deviceLabel>",
          prejoinPageEnabled: false,
          roomName: this.room,
          height: 500,
          parentNode: document.getElementById("jitsi-container"),
          interfaceConfigOverwrite: {
            filmStripOnly: false,
            SHOW_JITSI_WATERMARK: false,
            TOOLBAR_BUTTONS: [
              "microphone",
              "camera",
              "closedcaptions",
              "desktop",
              "fullscreen",
              "fodeviceselection",
              "hangup",
              "profile",
              "info",
              "chat",
              "recording",
              "livestreaming",
              "etherpad",
              "sharedvideo",
              "settings",
              "raisehand",
              "videoquality",
              "filmstrip",
              "invite",
              "feedback",
              "stats",
              "shortcuts",
              "tileview",
            ],
          },
          configOverwrite: {
            disableSimulcast: false,
          },
          teacherName: "",
          romm: "",
        };

        this.api = new JitsiMeetExternalAPI(domain, options);
        this.api.addEventListener("videoConferenceJoined", () => {
          console.log("Local User Joined");

          _this.api.executeCommand("displayName", _this.username);
          _this.api.executeCommand("password", _this.roomPassword);
        });
      } catch (error) {
        console.error("Failed to load Jitsi API", error);
      }
    },
    openRoom() {
      // verify the JitsiMeetExternalAPI constructor is added to the global..
      // if (this.teacherName != "" || this.room != "") {
      //   if (window.JitsiMeetExternalAPI) {
      //     // var person = prompt("Please enter your name:", "Rabie");
      //     if (person != null || person != "") this.username = this.teacherName;
      //     var room = prompt("Please enter your room:", "Test Room");
      //     if (room != null || room != "") this.room = this.room;
      //     this.startConference();
      //   } else alert("Jitsi Meet API script not loaded");
      // }
    },

    createRoom(classId) {
      this.showLoader = true;
      var classId = {
        classId: classId,
      };
      http()
        .post("/createLiveClasses", {
          classId: this.$route.query.classId,
          courseId: this.$route.query.courseId,
          chapterId: this.$route.query.chapterId,
        })
        .then((response) => {
          // this.addSection = response.data.data;
          console.log("CREATE___ROOOM", response.data);
          this.room = response.data.data.roomName;

          // this.username = response.data.data.LiveClasses.teacherName;
          this.roomPassword = response.data.data.password;

          var this_ = this;
          if (this.username != "" || this.room != "") {
            if (window.JitsiMeetExternalAPI) {
              // var person = prompt("Please enter your name:", "Rabie");
              if (this_.username != null || this_.username != "") {
                this.username = this.username;
              }
              // var room = prompt("Please enter your room:", "Test Room");
              if (this_.room != null || this_.room != "") {
                this.room = this.room;
              }
              this.startConference();
            } else alert("Jitsi Meet API script not loaded");
          }
          console.log("bazinga");
          this.showLoader = false;
        })
        .catch((err) => {
          this.showLoader = false;
        });
    },
    async studentClasses() {
      /* getLiveClassesesList - To up date line under heading*/
      let response = await this.getLiveClassesesList({
        classId: this.$route.query.classId,
        courseId: this.$route.query.courseId,
        chapterId: this.$route.query.chapterId,
      });
      console.log("response getLiveClassesesList- ", response);

      /* CHECK RESPONSE TO ASSIGN MESSAGE INSIDE BUTTON */
      if (response.data.data.length == 0) {
        this.startLiveSession = "Start Session";
        this.studentBtn = "";
      } else {
        this.liveLink = response.data.data[0].link;
        this.room = response.data.data[0].roomName;
        this.username = response.data.data[0].teacherId.name;
        this.roomPassword = response.data.data[0].password;
        // this.room = response.data.data[0].roomName;
        var this_ = this;
        console.log(this.room, this.roomPassword, this.username);

        // // this.username = response.data.data.LiveClasses.teacherName;
        // this.roomPassword = response.data.data[0].password;
        // var this_ = this;
        if (this.username != "" || this.room != "") {
          if (window.JitsiMeetExternalAPI) {
            // var person = prompt("Please enter your name:", "Rabie");
            if (this_.username != null || this_.username != "") {
              this.username = this.username;
            }
            // var room = prompt("Please enter your room:", "Test Room");
            if (this_.room != null || this_.room != "") {
              this.room = this.room;
            }
            this.startConference();
          }
        }

        if (response.data.data[0].sessionStatus == "ENDED") {
          // this.startLiveSession = "Start Session";
          this.studentBtn = "";
        }
        if (response.data.data[0].sessionStatus == "STARTED") {
          // this.startLiveSession = "Join Session";
          this.studentBtn = "Join Session";
        }
      }
    },
  },

  mounted() {
    this.token = this.$store.state.token;
  },
  async created() {
    if (this.$store.state.role === "PARENT") {
      this.studentClasses();
    }

    /* getStudentCourses - to get courseData - defined in GetApis.js*/
    if (this.$store.state.role === "PARENT") {
      await this.getStudentCourses({
        classId: localStorage.getItem("parentClassId"),
        studentId: localStorage.getItem("parentStudentId"),
      });
    }
  },
};
</script>
<style scoped>
.side-bar-color {
  color: #827bfa !important;
  /* border-top-right-radius: 74px !important; */
}
.card-border {
  border: 1px #bdbdbd solid;
  border-radius: 3px;
}
.reply-desc {
  border: 1px solid #f2f2f2;
}
.open-dialog-button {
  background: #827bfa !important;
  border-color: #827bfa !important;
  text-transform: none !important;
}

.reply-btn {
  background: #feb83c !important;
  border-color: #feb83c !important;
  text-transform: none !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}
#jitsi-container {
  height: 100vh;
}
</style>