<template>
  <b-card no-body tag="article" class="text-card">
    <b-overlay class="h-100" :show="loading">
      <div v-if="text" class="container-fill">
        <b-card-header header-tag="header">
          <h4>
            <template v-if="text.type === 'Textref'">
              <span>{{ toCommaList(text.authors) }},</span>
              <span>{{ text.title }},</span>
              <span>{{ text.edition }}</span>
            </template>
            <template v-else>
              {{ text.title }}
            </template>
          </h4>

          <slot name="header-extra" :text="text" />
        </b-card-header>

        <b-card-body v-html="text.content" :class="ellipsis ? 'ellipsis' : 'overflow-auto'" />

        <b-card-footer>
          <b-badge
            v-for="tag in text.tags" :key="tag.id"
            variant="dark" pill
          >
            {{ tag.name }}
          </b-badge>

          <slot name="footer-extra" v-bind="{ text, toCommaList }" />
        </b-card-footer>
      </div>
    </b-overlay>
  </b-card>
</template>

<script>
export default {
  name: 'TextCardBase',

  props: {
    id: { type: Number, required: true },
    textData: { type: Object, default: null },
    ellipsis: { type: Boolean, default: false }
  },

  data () {
    return {
      loading: this.textData === null,
      text: this.textData
    }
  },

  methods: {
    toCommaList (arr) {
      // FIXME TEMP some texts doesn't have authors
      try {
        return arr.map(({ name }) => name).join(', ')
      } catch {
        return arr
      }
    }
  },

  created () {
    if (this.text !== null) return
    this.$store.dispatch('GET_TEXT', { id: this.id }).then((text) => {
      this.text = text
      this.loading = false
    })
  }
}
</script>

<style lang="scss" scoped>
article {
  height: 100%;
}

header {
  display: flex;

  h4 {
    display: flex;
    flex-direction: column;
  }
}

.ellipsis {
  max-height: 10rem;
  overflow: hidden;
}
</style>
