<template>
  <a
    class="btn btn-sm btn-misc change-icon"
    :title="$t('write_comment')"
    @click="openModal"
    ><i class="fa fa-pencil-square-o" />
  </a>

  <teleport to="body">
    <modal
      v-if="modal.showModal"
      :modal-dialog-class="modal.modalDialogClass"
      @close="modal.showModal = false"
    >
      <template #header>
        <h3 class="modal-title">
          {{ $t("write_comment_about", { r: resource.resource.text }) }}
        </h3>
      </template>
      <template #body>
        <comment-editor v-model="content" />
      </template>
      <template #footer>
        <a class="btn btn-save" @click="saveAction">
          {{ $t("action.save") }}
        </a>
      </template>
    </modal>
  </teleport>
</template>

<script>
import Modal from "ChillMainAssets/vuejs/_components/Modal.vue";
import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";
import CommentEditor from "ChillMainAssets/vuejs/_components/CommentEditor/CommentEditor.vue";

export default {
  name: "WriteComment",
  components: {
    Modal,
    CommentEditor,
  },
  props: ["resource"],
  emits: ["updateComment"],
  data() {
    return {
      modal: {
        showModal: false,
        modalDialogClass: "modal-dialog-scrollable modal-xl",
      },
      formdata: {
        content: this.resource.comment,
      },
    };
  },
  i18n: {
    messages: {
      fr: {
        write_comment: "Écrire un commentaire",
        write_comment_about: "Écrire un commentaire à propos de {r}",
        comment_placeholder: "Commencez à écrire...",
      },
    },
  },
  computed: {
    editor: () => ClassicEditor,
    editorConfig: () => classicEditorConfig,
    content: {
      set(value) {
        this.formdata.content = value;
      },
      get() {
        return this.formdata.content;
      },
    },
  },
  methods: {
    openModal() {
      //console.log('write comment for', this.resource.resource.type, this.resource.resource.id);
      this.modal.showModal = true;
    },
    saveAction() {
      //console.log('save comment', this.resource.id, this.formdata.content);
      this.patchResource(this.resource.id, this.formdata.content);
    },
    patchResource(id, comment) {
      let url = `/api/1.0/person/accompanying-period/resource/${id}.json`,
        body = {
          type: "accompanying_period_resource",
          comment: comment,
        };
      makeFetch("PATCH", url, body).then((r) => {
        let resource = {
          type: "accompanying_period_resource",
          id: r.id,
          comment: r.comment,
          resource: r.resource,
        };
        this.$emit("updateComment", resource);
        this.modal.showModal = false;
      });
    },
  },
};
</script>
