<template>
  <div class="vue-component">
    <h2><a id="section-100" />{{ $t("comment.title") }}</h2>

    <!--div class="error flash_message" v-if="errors.length > 0">
         {{ errors[0] }}
         TODO fix errors flashbag for app component
      </div-->

    <div>
      <form @submit.prevent="submitform">
        <label class="col-form-label" for="content">{{
          $t("comment.label")
        }}</label>

        <comment-editor v-model="content" />

        <div class="sub-comment">
          <div
            v-if="
              pinnedComment !== null &&
              typeof pinnedComment.creator !== 'undefined'
            "
            class="metadata"
          >
            {{
              $t("comment.created_by", [
                pinnedComment.creator.text,
                $d(pinnedComment.updatedAt.datetime, "long"),
              ])
            }}
          </div>
          <div class="loading">
            <i
              v-if="loading"
              class="fa fa-circle-o-notch fa-spin"
              :title="$t('loading')"
            />
          </div>
        </div>

        <div>
          <ul class="record_actions">
            <li v-if="pinnedComment !== null">
              <a class="btn btn-delete" @click="removeComment">
                {{ $t("action.delete") }}
              </a>
            </li>
          </ul>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import CommentEditor from "ChillMainAssets/vuejs/_components/CommentEditor/CommentEditor.vue";
import { mapState } from "vuex";

export default {
  name: "Comment",
  components: {
    CommentEditor,
  },
  data() {
    return {
      loading: false,
      lastRecordedContent: null,
    };
  },
  computed: {
    ...mapState({
      pinnedComment: (state) => state.accompanyingCourse.pinnedComment,
    }),
    classicEditor: () => ClassicEditor,
    editorConfig: () => classicEditorConfig,
    content: {
      set(value) {
        console.log("new comment value", value);
        console.log("previous value", this.lastRecordedContent);
        this.lastRecordedContent = value;

        setTimeout(() => {
          console.log("performing test on ", value);
          if (this.lastRecordedContent === value) {
            this.loading = true;
            if (value !== "") {
              this.$store
                .dispatch("updatePinnedComment", value)
                .then(() => {
                  this.loading = false;
                })
                .catch(({ name, violations }) => {
                  if (
                    name === "ValidationException" ||
                    name === "AccessException"
                  ) {
                    violations.forEach((violation) =>
                      this.$toast.open({
                        message: violation,
                      }),
                    );
                  } else {
                    this.$toast.open({
                      message: "An error occurred",
                    });
                  }
                });
            } else {
              if (this.$store.state.accompanyingCourse.pinnedComment !== null) {
                this.$store
                  .dispatch("removePinnedComment", {
                    id: this.pinnedComment.id,
                  })
                  .then(() => {
                    this.loading = false;
                    this.lastRecoredContent = null;
                  })
                  .catch(({ name, violations }) => {
                    if (
                      name === "ValidationException" ||
                      name === "AccessException"
                    ) {
                      violations.forEach((violation) =>
                        this.$toast.open({
                          message: violation,
                        }),
                      );
                    } else {
                      this.$toast.open({
                        message: "An error occurred",
                      });
                    }
                  });
              }
            }
          }
        }, 3000);
      },
      get() {
        return this.pinnedComment ? this.pinnedComment.content : "";
      },
    },
    errors() {
      return this.$store.state.errorMsg;
    },
  },
  methods: {
    removeComment() {
      this.$store
        .dispatch("removePinnedComment", { id: this.pinnedComment.id })
        .catch(({ name, violations }) => {
          if (name === "ValidationException" || name === "AccessException") {
            violations.forEach((violation) =>
              this.$toast.open({ message: violation }),
            );
          } else {
            this.$toast.open({ message: "An error occurred" });
          }
        });
    },
  },
};
</script>

<style lang="scss">
div.ck-editor.ck-reset {
  margin: 0.6em 0;
}
div.sub-comment {
  display: flex;
  justify-content: space-between;
  div.loading {
    margin-right: 6px;
    margin-left: 6px;
  }
}
</style>
