<template>
  <div v-if="loading">
    <div class="row">
      <div class="col-9 col-md-9 col-sm-12 col-xs-12">
        <div class="column skeleton q-ml-xl">
          <q-skeleton type="text" width="80%" />
          <q-skeleton type="text" width="78%" />
          <q-skeleton type="text" width="65%" />
          <q-skeleton type="text" width="55%" />
          <q-skeleton type="text" width="80%" />
          <q-skeleton type="text" width="70%" />
          <q-skeleton type="text" width="67%" />
          <q-skeleton type="text" width="78%" />
          <q-skeleton type="text" width="65%" />
          <q-skeleton type="text" width="55%" />
          <q-skeleton type="text" width="80%" />
          <q-skeleton type="text" width="70%" />
          <q-skeleton type="text" width="67%" />
          <q-skeleton type="text" width="78%" />
          <q-skeleton type="text" width="65%" />
          <q-skeleton type="text" width="55%" />
        </div>
      </div>
    </div>
  </div>
  <div class="q-mx-lg" v-else>
    <q-card class="q-pa-sm q-mb-md">
      <div class="q-pa-sm bg-grey-2" v-if="isLoggedIn">
        <q-input
          type="input"
          bottom-slots
          v-model="newComment.comment"
          label="Share your comments here.."
          counter
          maxlength="200"
        >
          <template v-slot:before>
            <q-avatar size="50px">
              <q-img :src="authUserImageUrl" />
            </q-avatar>
          </template>

          <template v-slot:append>
            <q-icon
              v-if="newComment.comment !== ''"
              name="close"
              @click="newComment.comment = ''"
              class="cursor-pointer"
            />
          </template>
          <template v-slot:after>
            <q-btn
              :dense="$q.screen.lt.sm"
              color="secondary"
              :disabled="newComment.comment.length==0 || requestInProgress"
              @click="postComment()"
              :loading="requestInProgress"
            >
              <template v-slot:loading>
                <q-spinner-hourglass class="on-left" />...
              </template>
              POST
            </q-btn>
          </template>
        </q-input>
      </div>
      <div v-else>
        <router-link to="/login"></router-link>
        <q-btn class="q-ma-xl full-width" color="primary" to="/login" label="Login To Comment"></q-btn>
      </div>

      <div class="q-my-md">
        <q-list style="max-width: 100%">
          <q-item-label header>
            All Comments
            <q-badge color="grey" text-color="white text-bold" :label="commentsCount" />
          </q-item-label>
          <div v-for="(c,index) in comments" :key="c.id">
            <q-item>
              <q-item-section avatar>
                <q-avatar>
                  <q-img :src="commentorImageUrl(c.user)" />
                </q-avatar>
              </q-item-section>

              <q-item-section>
                <q-item-label lines="1">{{c.user.fname}} {{c.user.lname}}</q-item-label>
                <q-item-label caption lines="100">
                  <!-- <span class="text-weight-bold">Janet</span> -->
                  {{c.comment}}
                </q-item-label>
                <q-item-label caption lines="1">
                  <span>
                    <a href="#">
                      <i class="fas fa-thumbs-up q-pa-sm"></i>
                    </a>
                    95
                  </span>
                  <span>
                    <a href="#">
                      <i class="fas fa-thumbs-down q-pa-sm"></i>
                    </a>55
                  </span>
                  <a class="link" @click="showReplyBox(c.id,c.user)">
                    <span class="q-ml-sm">REPLY</span>
                  </a>
                </q-item-label>
              </q-item-section>

              <q-item-section side top>{{parseDateTime(c.created_at)}}</q-item-section>
            </q-item>

            <q-separator inset="item" v-if="index!=comments.length-1" />
            <q-item class="q-ml-lg" v-for="r in c.replies" :key="r.id">
              <q-item-section avatar>
                <q-avatar>
                  <q-img :src="commentorImageUrl(r.user)" />
                </q-avatar>
              </q-item-section>

              <q-item-section>
                <q-item-label lines="1">{{r.user.fname}} {{r.user.lname}}</q-item-label>
                <q-item-label caption lines="100">
                  <!-- <span class="text-weight-bold">John</span> -->
                  {{r.comment}}
                </q-item-label>
                <q-item-label caption lines="1">
                  <span>
                    <a href="#">
                      <i class="fas fa-thumbs-up q-pa-sm"></i>
                    </a>
                    95
                  </span>
                  <span>
                    <a href="#">
                      <i class="fas fa-thumbs-down q-pa-sm"></i>
                    </a>55
                  </span>
                  <a class="link" @click="showReplyBox(c.id,r.user)">
                    <span class="q-ml-sm">REPLY</span>
                  </a>
                </q-item-label>
              </q-item-section>

              <q-item-section side top>{{parseDateTime(r.created_at)}}</q-item-section>
            </q-item>
           
            <div v-if="isLoggedIn && validateReplyBoxState(c.id)">
              <q-separator inset="item" />
              <q-item class="q-ml-lg">
                <q-item-section>
                  <q-input
                    type="input"
                    bottom-slots
                    v-model="newCommentReply.comment"
                    label="Share your reply here.."
                    counter
                    maxlength="200"
                  >
                    <template v-slot:before>
                      <q-avatar size="50px">
                        <q-img :src="authUserImageUrl" />
                      </q-avatar>
                    </template>

                    <template v-slot:append>
                      <q-icon
                        v-if="newCommentReply.comment !== ''"
                        name="close"
                        @click="newCommentReply.comment = ''"
                        class="cursor-pointer"
                      />
                    </template>
                    <template v-slot:after>
                      <q-btn :dense="$q.screen.lt.sm" @click="hideReplyBox(c.id)">Cancel</q-btn>
                      <q-btn
                        :dense="$q.screen.lt.sm"
                        color="secondary"
                        :disabled="newCommentReply.comment.length==0 || requestInProgress"
                        @click="postReply(c.id)"
                        :loading="requestInProgress"
                      >
                        <template v-slot:loading>
                          <q-spinner-hourglass class="on-left" />...
                        </template>
                        REPLY
                      </q-btn>
                    </template>
                  </q-input>
                </q-item-section>
              </q-item>
            </div>
          </div>
        </q-list>
      </div>
      <q-btn
        class="q-ma-xl full-width"
        color="primary"
        label="Show more comments"
        :loading="loadingCommets"
        @click="showMoreComments()"
        v-show="nextCommentsUrl"
      >
        <template v-slot:loading>
          <q-spinner-hourglass class="on-left" />Loading...
        </template>
      </q-btn>
    </q-card>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { skeleton } from "../mixins/SkeletonMixin.js";
import moment from "moment-timezone";
export default {
  mixins: [skeleton],
  props: ["page"],
  data() {
    return {
      comments: [],
      newComment: {
        comment: "",
        page_id: this.page ? this.page.id : null,
      },
      newCommentReply: {
        comment: "",
        page_id: this.page ? this.page.id : null,
        comment_id: "",
      },
      commentReplyBoxState: [],
      requestInProgress: false,
      NoOFcommentsToShow: 4,
      nextCommentsUrl: null,
      loadingCommets: false,
      timezone: "",
    };
  },
  computed: {
    ...mapGetters("auth", ["isLoggedIn", "authUserName", "authUserImageUrl"]),
    commentsCount() {
      let count = this.comments.length;
      let repliesCount = this.comments
        .map((val, index) => {
          return val.replies.length;
        })
        .reduce((acc, val) => {
          return acc + val;
        }, 0);

      return count + repliesCount;
    },
  },
  mounted() {
    this.fetchComments();
    this.timezone = this.getLocalTimezone();
  },
  methods: {
    fetchComments() {
      axios
        .get(`/page/${this.page.id}/comments`)
        .then((res) => {
          this.comments = res.data.data;
          this.nextCommentsUrl = res.data.next_page_url;
          this.comments.forEach((e) => {
            this.commentReplyBoxState.push({
              id: e.id,
              showBox: false,
              showReplies: false,
            });
          });
          this.newComment.page_id = this.page.id;
          this.newCommentReply.page_id = this.page.id;
          this.hideSkeletonLoader();
        })
        .catch((e) => {
          this.hideSkeletonLoader();
        });
    },
    showMoreComments() {
      this.loadingCommets = true;
      axios
        .get(this.nextCommentsUrl)
        .then((res) => {
          this.loadingCommets = false;
          res.data.data.forEach((e) => {
            this.comments.push(e);
            this.commentReplyBoxState.push({
              id: e.id,
              showBox: false,
              showReplies: false,
            });
          });

          this.nextCommentsUrl = res.data.next_page_url;
        })
        .catch((e) => {
          this.loadingCommets = false;
          this.$q.notify({
            type: "error-notify",
            position: "right",
            message: "Failed",
            caption: "Sorry!! Comment Loading Failed...",
            actions: [{ label: "Dismiss", color: "yellow", handler: () => {} }],
          });
        });
    },
    postComment() {
      let t = this;
      this.requestInProgress = true;
      axios
        .post("/page/add/comment", this.newComment)
        .then(function (res) {
          console.log(res.data);
          t.requestInProgress = false;
          t.$q.notify({
            type: "success-notify",
            position: "right",
            message: "Success",
            caption: res.data.msg,
            actions: [{ label: "Dismiss", color: "yellow", handler: () => {} }],
          });
          t.newComment.comment = "";
          t.fetchComments();
        })
        .catch(function (e) {
          t.$q.notify({
            type: "error-notify",
            position: "right",
            message: "Failed",
            caption: "Sorry!! Comment Failed",
            actions: [{ label: "Dismiss", color: "yellow", handler: () => {} }],
          });
          t.requestInProgress = false;
        });
    },
    postReply(id) {
      let comment = this.newCommentReply.comment;
      let t = this;
      axios
        .post("/page/add/comment/reply", {
          comment: comment,
          comment_id: id,
          page_id: this.page.id,
        })
        .then(function (res) {
          console.log(res.data);
          t.requestInProgress = false;
          t.$q.notify({
            type: "success-notify",
            position: "right",
            message: "Success",
            caption: res.data.msg,
            actions: [{ label: "Dismiss", color: "yellow", handler: () => {} }],
          });
          t.newCommentReply.comment = "";
          t.fetchComments();
        })
        .catch(function (e) {
          t.$q.notify({
            type: "error-notify",
            position: "right",
            message: "Failed",
            caption: "Sorry!! Reply Failed",
            actions: [{ label: "Dismiss", color: "yellow", handler: () => {} }],
          });
          t.requestInProgress = false;
        });
    },
    validateReplyBoxState: function (id) {
      var state = this.commentReplyBoxState.find((e) => {
        return e.id == id;
      });

      return state.showBox;
    },
    showReplyBox: function (id, user) {
      if (!this.isLoggedIn) {
        this.dialogFormVisible = true;
        return;
      }
      this.commentReplyBoxState.forEach((e, ind) => {
        this.commentReplyBoxState[ind].showBox = false;
      });
      var index = this.commentReplyBoxState.findIndex((e) => {
        return e.id == id;
      });

      this.commentReplyBoxState[index].showBox = !this.commentReplyBoxState[
        index
      ].showBox;
      if (this.commentReplyBoxState[index].showBox) {
        this.tag = `@${user.fname} ${user.lname} `;
      }
    },
    hideReplyBox: function (id) {
      var index = this.commentReplyBoxState.findIndex((e) => {
        return e.id == id;
      });
      this.commentReplyBoxState[index].showBox = false;
      this.newCommentReply.comment = "";
    },
    validateRepliesState: function (id) {
      var state = this.commentReplyBoxState.find((e) => {
        return e.id == id;
      });

      return state.showReplies;
    },
    showReplies: function (id) {
      var index = this.commentReplyBoxState.findIndex((e) => {
        return e.id == id;
      });
      this.commentReplyBoxState[index].showReplies = true;
    },
    hideReplies: function (id) {
      var index = this.commentReplyBoxState.findIndex((e) => {
        return e.id == id;
      });
      this.commentReplyBoxState[index].showReplies = false;
    },
    commentorImageUrl(user) {
      if (user.provider && user.avatar) {
        return user.avatar;
      } else {
        if (user.image) {
          return this.storageUrl + "user/s/" + user.image;
        }
        return "http://interfaceedu.docexams.com/storage/user/s/default.png";
      }
    },
    getLocalTimezone() {
      var timezone = moment.tz.guess();
      if (!timezone) {
        return "Asia/Dubai";
      }
      return timezone;
    },

    getLocalTime: function (date) {
      return moment
        .utc(date, "YYYY-MM-DD HH:mm:ss")
        .clone()
        .tz(this.timezone)
        .format("HH:mm:ss");
    },
    parseDateTime: function (date) {
      let t = moment.utc(date, "YYYY-MM-DD HH:mm:ss").clone().tz(this.timezone);
      let now = moment();
      return t.from(now);
    },
  },
};
</script>

<style lang="css" scoped>
.link {
  cursor: pointer;
}
</style>
