<template>
  <span>
    <TfPdfExport
      :button-size="buttonSize"
      :button-title="buttonTitle"
      :filename="`comments_${projectId}.pdf`"
      :is-disabled="!sortedComments.length"
    >
      <ExportHeader
        :employer-name="employerName"
        :filters="filters"
        title="Comment History"
      />
      <Comment
        v-for="comment in sortedComments"
        :key="comment.id"
        :broker="broker"
        :comment="comment"
        :documents="documents"
        :project-id="projectId"
        :is-pdf-render="true"
        :is-reply="!comment.topComment"
        :user-info="userInfo"
        application-namespace="export"
      />
    </TfPdfExport>
  </span>
</template>

<script>
  import ExportHeader from './Header';

  /**
   * PDF Exporter for Comments
   *
   * @vuedoc
   * @exports TfPdfExport/Comments
   * @category Components
   */
  export default {
    name: 'TfCommentsExport',
    components: { ExportHeader },
    props: {
      broker: {
        type: Object,
        default: () => ({}),
      },
      buttonSize: {
        type: String,
        default: 'text-icon',
      },
      buttonTitle: {
        type: String,
        default: 'export',
      },
      comments: {
        type: Array,
        default: () => [],
      },
      documents: {
        type: Array,
        default: () => [],
      },
      employerName: {
        type: String,
        default: null,
      },
      filters: {
        type: Object,
        default: () => ({}),
      },
      isDisabled: {
        type: Boolean,
        default: false,
      },
      projectId: {
        type: Number,
        default: null,
      },
      userInfo: {
        type: Object,
        required: true,
        default: () => ({
          firstName: '',
          lastName: '',
          organization: '',
          type: 'broker',
        }),
      },
    },
    computed: {
      /**
       * Sorts the comment replies in descending order and adds `topComment` to the top comments.
       * Then we return a flattened array of all comments.
       *
       * @returns {Array}
       */
      sortedComments() {
        return this.comments.reduce((comments, comment) => {
          const newComment = {
            ...comment,
            replies: [],
            topComment: true,
          };
          const sortedReplies = comment.replies
            ? this.$TF.Formatting.sortObjects(
              comment.replies,
              'created_at',
              'desc',
            )
            : [];

          return comments.concat([newComment], sortedReplies);
        }, []);
      },
    },
  };
</script>
