<template>
  <div>
    <client-only>
      <div class="detail-main__form">
        <form class="detail-form" method="post">
          <div class="detail-form__textarea">
            <textarea ref="commentText" v-model="text" name=""> </textarea>
            <transition name="fade">
            <v-sheet color="rgba(0,0,0,0)" v-if="infoText || errorText">
              <div class="detail-form__message" v-bind:style="infoText ? infoColor : errorColor">
              {{ infoText || errorText }}
              </div>
            </v-sheet>
            </transition>
          </div>
          <div class="detail-form__actions">
            <div @click="createComment" class="detail-form__action button button_grey-dark button_grey-dark-short">
              <span class="button__text">Отправить</span>
            </div>
            <div class="comment-response-label" v-if="response_user_name">
              <div class="comment-response-label__wrapper">
                Ответ для&ensp;<span class="comment-response-label__user">{{ response_user_name }}</span><span class="comment-response-label__clear" @click="clearResponse">&times;</span>
              </div>
            </div>
          </div>
        </form>
      </div>
    </client-only>
  </div>
</template>

<script>
export default {
  data: () => ({
    text: "",
    errorText: "",
    old_response_user_name: "",
    infoText: "",
    value: 0,
    interval: 0,
    disabled: false,
    errorColor:{
      color:"#ad0000"
    },
    infoColor:{
      color:"#3B9B00"
    },
  }),
  props: {
    pull_id: {
      type: String,
    },
    response_user_name: {
      type: String,
    },
    response_user_id: {
      type: String,
    },
  },
  watch: {
    response_user_name() {
      if(this.old_response_user_name){
        this.text = this.text.replaceAll(this.old_response_user_name + ", ", "");
      }
      if(this.text === "" && this.response_user_name !== ""){
        this.text = this.response_user_name + ", ";
      }
      this.old_response_user_name = this.response_user_name;
      this.$refs.commentText.focus();
    },
    value (val) {
        if (val < 100) return
        this.value = 0
        clearInterval(this.interval)
        this.infoText=""
        this.errorText=""
      },
    },
  methods: {
    createComment() {
      if (this.disabled) {
        return;
      }
      this.disabled = true
      this.$nuxt.$loading.start();
      let textComment = this.text;
      if(this.response_user_id){
        if(this.response_user_name){
          textComment = this.text.replaceAll(this.response_user_name + ", ", "");
        }
      }
      if(textComment === ""){
        this.errorText = "Ой-ой, вы ничего не написали…";
        this.$nuxt.$loading.finish();
        this.disabled = false
      }else{
        this.$axios
          .post(
            "/comments/create",
            {
              text: textComment,
              pull: this.pull_id,
              response_user_id: this.response_user_id,
            },
            {
              Headers: {
                AccessToken: this.$auth.strategy.token.get(),
              },
            }
          )
          .then((res) => {
            if(res.data.success){
              if(res.data.data.is_moderation) {
                this.infoText = "Комменатрий отправлен на модерацию.";
                this.startBuffer()
              }
              this.text = "";
              this.$emit('clearCommentResponse');
              this.$axios.get("/comments/pull_" + this.pull_id + (0 ? 'page_' + 0 : ''))
              .then((Comments) => {
                this.$emit('commentsResponseData', Comments.data.data);
              });
            }else{
              this.errorText = "Комментарий не отправлен. Уже разбираемся, почему…";
              console.error(res.data.errors);
            }
            this.$nuxt.$loading.finish();
            this.disabled = false
          })
          .catch((err) => {
            this.errorText = "Комментарий не отправлен. Уже разбираемся, почему…";
            console.error("Error sending comment");
            this.$nuxt.$loading.finish();
            this.disabled = false
          });
      }
    },
    clearResponse(){
      this.text = this.text.replaceAll(this.response_user_name + ", ", "");
      this.$emit('clearCommentResponse');
    },
    startBuffer () {
      clearInterval(this.interval)
      this.interval = setInterval(() => {
        this.value += 100
      }, 5000)
    },
   },
};
</script>

<style>
</style>