<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 @click.prevent="deleteFile(file.id)" class="link-danger cursor-pointer">remove</a>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <vue-dropzone v-if="bookId"
        ref="myVueDropzone"
        id="dropzone"
        :options="dropzoneOptions"
        :useCustomSlot="true"
        @vdropzone-success="vdropzoneSuccess"
    >
      <div class="dropzone-custom-content">
        <h3 class="dropzone-custom-title">Drag and drop to upload content!</h3>
        <div class="subtitle">
          ...or click to select a file from your computer
        </div>
      </div>
    </vue-dropzone>
  </div>
</template>

<script>
import vue2Dropzone from "vue2-dropzone";
import {mapActions, mapState} from "vuex";

export default {
  name: 'Files',
  components: {
    vueDropzone: vue2Dropzone
  },
  data() {
    return {
      dropzoneOptions: {
        capture: 'image/',
        url: '/book/' + this.bookId,
        thumbnailWidth: 150,
        maxFilesize: 50.5,
        acceptedFiles: '.pdf, .epub, .mobi'
      }
    }
  },
  props: {
    bookId: {type: Number, default: null}
  },
  mounted() {
    this.getFiles(this.bookId);
  },
  computed: {
    ...mapState('filemodule', ['files'])
  },
  methods: {
    ...mapActions('filemodule', ['getFiles', 'deleteFile']),
    vdropzoneSuccess(file) {
      this.$refs.myVueDropzone.removeFile(file);
      this.getFiles(this.bookId);
    }
  }
}
</script>