<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>

    <!-- DIALOG TO ADD COURSE DISCUSSION FORUM -->
    <v-dialog v-model="addForumDialog" max-width="500" persistent>
      <v-card flat class="card-style pa-2" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Forum</label>
            <v-icon size="24" class="right" @click="addForumDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-layout align-center>
            <v-flex xs12>
              <v-flex xs12 sm12>
                <v-form ref="form" v-model="valid" lazy-validation>
                  <v-layout>
                    <v-flex
                      xs12
                      class="text-xs-center text-sm-center text-md-center text-lg-center"
                    >
                      <v-avatar size="100px" v-if="!imageUrl">
                        <img src="/static/icon/user.png" />
                      </v-avatar>
                      <input
                        type="file"
                        style="display: none"
                        ref="image"
                        accept="image/*"
                        @change="onFilePicked"
                      />
                      <img
                        :src="imageData.imageUrl"
                        height="150"
                        width="150"
                        v-if="imageUrl"
                        style="border-radius:50%; width:200px"
                      />
                    </v-flex>
                  </v-layout>

                  <v-layout wrap>
                    <!-- SUBJECT -->
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 sm4 class="pt-4 subheading">
                          <label class="right hidden-xs-only hidden-sm-only">Subject:</label>
                          <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Subject:</label>
                        </v-flex>
                        <v-flex xs8 sm8 class="ml-3">
                          <v-text-field
                            v-model="addForumParams.subject"
                            placeholder="subject"
                            type="text"
                            :rules="cantBeEmpty"
                            required
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <!-- DESCRIPTION -->
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 sm4 class="pt-4 subheading">
                          <label class="right hidden-xs-only hidden-sm-only">Description:</label>
                          <label
                            class="right hidden-lg-only hidden-md-only hidden-xl-only"
                          >Description:</label>
                        </v-flex>
                        <v-flex xs8 sm8 class="ml-3">
                          <v-text-field
                            v-model="addForumParams.description"
                            placeholder="Description"
                            type="text"
                            :rules="cantBeEmpty"
                            required
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                    <!-- UPLOAD IMAGE -->
                    <v-flex xs12 sm12>
                      <v-layout>
                        <v-flex xs4 class="pt-4 subheading">
                          <label class="right hidden-xs-only hidden-sm-only">Upload Image:</label>
                          <label class="right hidden-lg-only hidden-md-only hidden-xl-only">Upload :</label>
                        </v-flex>
                        <v-flex xs8 class="ml-3">
                          <v-text-field
                            label="Select Image"
                            @click="pickFile"
                            v-model="imageName"
                            append-icon="attach_file"
                          ></v-text-field>
                        </v-flex>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                  <v-layout>
                    <v-flex xs12 sm12>
                      <v-layout class="right">
                        <v-btn @click="submit" round dark :loading="loading" class="add-button">Add</v-btn>
                      </v-layout>
                    </v-flex>
                  </v-layout>
                </v-form>
              </v-flex>
            </v-flex>
          </v-layout>
        </v-container>
      </v-card>
    </v-dialog>

    <v-container grid-list-xl class="pt-0">
      <v-layout row wrap class="mt-1">
        <v-flex xs12 sm12 md9>
          <v-layout column>
            <!-- HEADING -->
            <v-flex>
              <div class="title side-bar-color font-weight-bold">Course Discussion Forum</div>
              <div class="subheading grey--text lighten-1">General news and announcements</div>
            </v-flex>

            <!-- ADD DISCUSSION FORUM BUTTON -->
            <v-flex>
              <div>
                <v-btn
                  fab
                  dark
                  class="open-dialog-button hidden-xl-only hidden-md-only hidden-lg-only"
                  small
                  @click="addForumDialog = true"
                >
                  <v-icon dark>add</v-icon>
                </v-btn>
                <v-btn
                  round
                  class="open-dialog-button hidden-sm-only hidden-xs-only"
                  dark
                  @click="addForumDialog = true"
                >
                  <v-icon class="white--text pr-1" size="20">add</v-icon>Add A New Discussion Topic
                </v-btn>
              </div>
            </v-flex>

            <!-- DATA TABLE -->
            <v-flex>
              <v-data-table
                :headers="courseDiscussionHeaders"
                :items="courseDiscussionItems"
                :pagination.sync="pagination"
                :search="search"
                item-key="_id"
              >
                <template slot="items" slot-scope="props">
                  <tr
                    class="tr"
                    @click="props.expanded = !props.expanded;courseDiscussionId = props.item._id;getDiscussionesThread(props.item._id)"
                  >
                    <td class="text-xs-center td td-row">
                      <v-avatar size="40">
                        <img :src="props.item.attachementUrl" v-if="props.item.attachementUrl" />
                        <img src="/static/icon/user.png" v-else-if="!props.item.attachementUrl" />
                      </v-avatar>
                    </td>
                    <td class="td td-row text-xs-center">{{ props.item.subject}}</td>
                    <td class="td td-row text-xs-center">{{ props.item.studentId.name }}</td>
                    <td class="td td-row text-xs-center">-</td>
                    <td class="td td-row text-xs-center">{{ props.item.forumThread.length }}</td>
                  </tr>
                </template>
                <template slot="expand" slot-scope="props">
                  <v-layout>
                    <v-flex xs12 v-for="(courseDiscussionData,i) in courseDiscussionData" :key="i">
                      <v-card class="elevation-0 grey lighten-3 pa-2" flat>
                        <v-list two-line subheader>
                          <v-list-tile>
                            <v-list-tile-avatar>
                              <v-avatar size="46">
                                <img
                                  :src="courseDiscussionData.attachementUrl"
                                  v-if="courseDiscussionData.attachementUrl"
                                />
                                <img
                                  src="/static/icon/user.png"
                                  v-else-if="!courseDiscussionData.attachementUrl"
                                />
                              </v-avatar>
                            </v-list-tile-avatar>
                            <v-list-tile-content>
                              <v-list-tile-title>{{ courseDiscussionData.subject }}</v-list-tile-title>
                              <v-list-tile-sub-title>
                                By
                                <span class="info--text">{{ courseDiscussionData.studentId.name }}</span>
                                - {{dates(courseDiscussionData.created ) }}
                              </v-list-tile-sub-title>
                            </v-list-tile-content>
                            <v-list-tile-action>
                              <div>
                                <v-btn
                                  flat
                                  round
                                  dark
                                  class="reply-btn"
                                  @click="showReplyBox = true"
                                >Reply</v-btn>
                              </div>
                            </v-list-tile-action>
                          </v-list-tile>
                        </v-list>
                      </v-card>
                      <v-flex xs12 class="mt-4" v-show="showReplyBox">
                        <v-textarea
                          name="input-7-1"
                          solo
                          label="Label Text"
                          multi-line
                          v-model="replyDescription"
                        ></v-textarea>
                        <v-btn
                          round
                          dark
                          class="open-dialog-button"
                          flat
                          @click="showReplyBox = false"
                        >Cancel</v-btn>
                        <v-btn
                          round
                          dark
                          :loading="loading"
                          class="reply-btn"
                          @click="replyThreadDiscussion(props.item)"
                        >Submit</v-btn>
                      </v-flex>
                      <v-flex
                        xs12
                        class="mt-4 pl-5 mx-auto"
                        v-for="(replyThread,i) in courseDiscussionData.forumThread"
                        :key="i"
                      >
                        <v-card class="elevation-0 grey lighten-3" flat>
                          <v-list two-line subheader class="grey lighten-3 pa-1">
                            <v-list-tile>
                              <v-list-tile-avatar>
                                <v-avatar size="46">
                                  <img
                                    :src="courseDiscussionData.attachementUrl"
                                    v-if="courseDiscussionData.attachementUrl"
                                  />
                                  <img
                                    src="/static/icon/user.png"
                                    v-else-if="!courseDiscussionData.attachementUrl"
                                  />
                                </v-avatar>
                              </v-list-tile-avatar>
                              <v-list-tile-content>
                                <v-list-tile-title>Re: {{ courseDiscussionData.subject }}</v-list-tile-title>
                                <v-list-tile-sub-title>
                                  By
                                  <span
                                    class="info--text"
                                    v-if="replyThread.studentId"
                                  >{{ replyThread.studentId.name }}</span>
                                  - {{dates(replyThread.created ) }}
                                </v-list-tile-sub-title>
                              </v-list-tile-content>
                            </v-list-tile>
                          </v-list>
                          <v-list class="pa-2 reply-desc">
                            <v-list-tile-content>
                              <v-list-tile-title
                                v-show="replyThread.showDescriptionReplyThread"
                              >{{ replyThread.description }}</v-list-tile-title>
                              <v-flex
                                xs12
                                sm12
                                md4
                                v-show="replyThread.showUpdateReplyThread == true"
                              >
                                <v-text-field v-model="replyThread.description"></v-text-field>
                                <v-btn
                                  flat
                                  round
                                  dark
                                  class="reply-btn right"
                                  @click="updateRelpyThreadDiscussion(replyThread,props.item)"
                                >Save</v-btn>
                              </v-flex>
                            </v-list-tile-content>
                          </v-list>
                          <v-list class="grey lighten-4 pa-0">
                            <v-list-tile-action>
                              <v-spacer></v-spacer>
                              <div>
                                <v-btn
                                  flat
                                  round
                                  dark
                                  class="reply-btn"
                                  @click="deleteRelpyThreadDiscussion(replyThread._id,props.item._id)"
                                >Delete</v-btn>
                                <v-btn
                                  flat
                                  round
                                  dark
                                  class="reply-btn mr-4"
                                  @click="showUpdateReplyThreadDiscussion(replyThread)"
                                >Edit</v-btn>
                              </div>
                            </v-list-tile-action>
                          </v-list>
                        </v-card>
                      </v-flex>
                    </v-flex>
                  </v-layout>
                </template>
                <v-alert
                  slot="no-results"
                  :value="true"
                  color="error"
                  icon="warning"
                >Your search for "{{ search }}" found no results.</v-alert>
              </v-data-table>
            </v-flex>
          </v-layout>
        </v-flex>

        <v-spacer></v-spacer>

        <!-- COURSES - positioned to the right of the page -->
        <v-flex xs12 sm12 md3>
          <v-card class="elevation-0 card-border" height="100%">
            <v-container class="pt-0">
              <div class="side-bar-color font-weight-bold title">Courses</div>

              <div v-for="(course,index) in courseData">
                <v-btn
                  flat
                  class="subheading text-xs-start justify-left"
                  style="cursor: pointer;"
                  block
                  @click="routeToCourseDetails(course._id)"
                >
                  <div style="width: 100%;text-align: left;">
                    <v-icon style="color: red;padding-bottom: 3px;" size="15">play_arrow</v-icon>
                    {{course.courseName}}
                  </div>
                </v-btn>
              </div>
            </v-container>
          </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";
export default {
  mixins: [AllApiCalls],
  data() {
    return {
      valid: true,
      addForumDialog: false,
      addForumParams: {},
      // UPLOAD IMAGE
      imageName: "",
      imageUrl: "",
      imageFile: "",
      imageData: {},

      // DATA TABLE
      search: "",
      pagination: {
        rowsPerPage: 10
      },
      courseDiscussionHeaders: [
        {
          text: "Image",
          value: "attachementUrl",
          sortable: false,
          align: "center"
        },
        {
          text: "Discussion",
          align: "center",
          sortable: false,
          value: ""
        },
        {
          text: "Started",
          value: "",
          sortable: false,
          align: "center"
        },
        { text: "Last Pot", value: "", sortable: false, align: "center" },
        { text: "Replies", value: "", sortable: false, align: "center" }
      ],
      courseDiscussionItems: [],

      // COURSE DISCUSSION REPLTY FUNCTIONALITY
      courseDiscussionId: "",
      showReplyBox: false,
      courseDiscussionData: [],
      replyDescription: "",
      loginId: "",
      editedIndex: -1
    };
  },
  methods: {
    dates: function(date) {
      return moment(date).format("MMMM DD, YYYY hh:mm A");
    },
    /* UPLOAD IMAGE */
    pickFile() {
      this.$refs.image.click();
    },

    onFilePicked(e) {
      // console.log(e)
      const files = e.target.files;
      this.imageData.upload = e.target.files[0];
      if (files[0] !== undefined) {
        this.imageName = files[0].name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.imageUrl = fr.result;
          this.imageFile = files[0]; // this is an image file that can be sent to server...
          this.imageData.imageUrl = URL.createObjectURL(this.imageFile);
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },
    async submit() {
      if (this.$refs.form.validate()) {
        this.addForumParams.classId = localStorage.getItem("parentClassId");
        this.addForumParams.courseId = this.$route.query.courseId;
        this.addForumParams.studentId = localStorage.getItem("parentStudentId");

        if (this.imageUrl) {
          var str = this.imageUrl;
          const [baseUrl, imageUrl] = str.split(/,/);
          this.addForumParams.upload = imageUrl;
        }
        this.loading = true;
        await http()
          .post("/createCourseDiscussion", this.addForumParams)
          .then(response => {
            this.snackbar = true;
            this.text = "Discussion added successfully";
            this.snackbarColor = "green";
            this.addForumDialog = false;
            this.clear();
            this.loading = false;
            console.log("response of createCourseDiscussion - ", response);
          })
          .catch(error => {
            this.snackbar = true;
            this.text = error.response.data.message;
            this.snackbarColor = "error";
            this.loading = false;
          });

        /* getCourseDiscussionesList - to populate the data table */
        await this.getCourseDiscussionesList({
          courseId: this.$route.query.courseId,
          classId: localStorage.getItem("parentClassId")
        });
        this.addForumDialog = false;
      }
    },
    clear() {
      this.$refs.form.reset();
      this.imageUrl = "";
    },
    async routeToCourseDetails(courseId) {
      /* getParticularCourseDetail- To get courseDetail - defined in GetApis.js*/
      let response = await this.getParticularCourseDetail(courseId);

      /* If the response is null then dont route */
      if (response.data.data.length > 0) {
        this.$router.push({
          name: "Course Details",
          query: { courseId: courseId }
        });
      } else {
        this.seeSnackbar("No Data Available", "warning");
      }
    },

    // COURSE DISCUSSION REPLY FUNCTIONALITY

    getDiscussionesThread() {
      // console.log("id", this.getSelectedData.courseId);
      this.showLoader = true;
      http()
        .get("/getParticularCourseDiscussion", {
          params: {
            courseDiscussionId: this.courseDiscussionId
          }
        })
        .then(response => {
          //   console.log("response", response.data.data);
          this.courseDiscussionData = response.data.data;
          for (let i = 0; i < this.courseDiscussionData.length; i++) {
            for (
              let j = 0;
              j < this.courseDiscussionData[i].forumThread.length;
              j++
            ) {
              this.courseDiscussionData[i].forumThread[
                j
              ].showUpdateReplyThread = false;
              this.courseDiscussionData[i].forumThread[
                j
              ].showDescriptionReplyThread = true;
            }
          }
          this.showLoader = false;
          this.showReplyBox = false;
        })
        .catch(error => {
          console.log("err====>", error);
          this.showLoader = false;
        });
    },
    replyThreadDiscussion(selected) {
      this.showLoader = true;
      var payloadData = {
        courseDiscussionId: selected._id,
        studentId: selected.studentId._id,
        description: this.replyDescription
      };
      http()
        .put("/replyForumThread", payloadData)
        .then(response => {
          //   console.log("response", response.data.data);
          this.showLoader = false;
          this.getDiscussionesThread();
        })
        .catch(error => {
          this.showLoader = false;
        });
    },
    showUpdateReplyThreadDiscussion(item) {
      this.editedIndex = this.courseDiscussionData.indexOf(item);
      var editedItem = Object.assign({}, item);
      var arrayOfcourseDiscussionData = [];
      for (let i = 0; i < this.courseDiscussionData.length; i++) {
        for (
          let j = 0;
          j < this.courseDiscussionData[i].forumThread.length;
          j++
        ) {
          if (
            editedItem._id == this.courseDiscussionData[i].forumThread[j]._id
          ) {
            this.courseDiscussionData[i].forumThread[
              j
            ].showUpdateReplyThread = true;
            this.courseDiscussionData[i].forumThread[
              j
            ].showDescriptionReplyThread = false;
          }
        }
        arrayOfcourseDiscussionData.push(this.courseDiscussionData[i]);
      }
      this.courseDiscussionData = arrayOfcourseDiscussionData;
    },
    updateRelpyThreadDiscussion(replyThread, selected) {
      this.showLoader = true;
      var payloadData = {
        forumThreadId: replyThread._id,
        courseDiscussionId: selected._id,
        studentId: selected.studentId._id,
        description: replyThread.description
      };
      http()
        .put("/updateForumThread", payloadData)
        .then(response => {
          this.showLoader = false;
          this.getDiscussionesThread();
        })
        .catch(error => {
          this.showLoader = false;
        });
    },
    deleteRelpyThreadDiscussion(id, courseDiscussionId) {
      this.showLoader = true;
      var payloadData = {
        forumThreadId: id,
        courseDiscussionId: courseDiscussionId
      };
      http()
        .put(
          "/deleteForumThread",
          confirm("Are you sure you want to delete this?") && payloadData
        )
        .then(response => {
          this.showLoader = false;
          this.getDiscussionesThread();
        })
        .catch(error => {
          this.showLoader = false;
        });
    }
  },
  async created() {
    this.loginId = this.$store.state.id;
    /* getStudentCourses - to get courseData - defined in GetApis.js*/
    await this.getStudentCourses({
      classId: localStorage.getItem("parentClassId"),
      studentId: localStorage.getItem("parentStudentId")
    });

    /* getCourseDiscussionesList - to populate the data table */
    await this.getCourseDiscussionesList({
      courseId: this.$route.query.courseId,
      classId: localStorage.getItem("parentClassId")
    });
  }
};
</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;
}
</style>