<template>
  <div>
    <h1>Files</h1>

    <div v-if="files.length">
      <table class="table">
        <thead>
        <tr>
          <th>File name</th>
          <th class="text-end">File size</th>
          <th>Extension</th>
          <th>Download</th>
          <th>Remove</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="file in files">
          <td>{{ file.file_name }}
            <p class="mb-0" v-if="file.book">
              <a class="text-decoration-none" :href="'/book/'+file.book.id">{{
                  file.book.title
                }}</a> <a href="" class="text-decoration-none link-secondary">{{ file.book.author }}</a>
            </p>
          </td>
          <td class="text-end">{{ file.file_size_human }}</td>
          <td>{{ file.extension }}</td>
          <td><a :href="'/file/'+ file.id" class="link-secondary">download</a></td>
          <td><a :href="'/file/delete/'+file.id" @click.prevent="deleteFile(file.id)" class="link-danger">remove</a>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import {EventBus} from "../event-bus";

export default {
  name: 'Files',
  components: {
    EventBus
  },
  data() {
    return {
      files: []
    }
  },
  props: {
    bookId: {type: Number, default: null}
  },
  mounted() {
    this.getFiles();
  },
  created() {
    window.EventBus.$on('fileUploaded', this.getFiles);
  },
  methods: {
    deleteFile: function (fileId) {
      axios.get(window.location.origin + '/file/delete/' + fileId).then(() => this.getFiles())
    },
    getFiles: function () {
      axios.get(this.getFilesEndpoint(),  {
        headers: {
          'accept': 'application/json'
        }
      }).then(response => this.files = response.data)
    },
    getFilesEndpoint: function () {
      if (this.bookId) {
        return `/api/books/${this.bookId}/files`;
      }
      return `/api/files`;
    }
  }
}
</script>