<template>
  <div id="file_library_view" class="view file_library-view" @keydown.esc="selectedFile = null" >
    <div class="view-title">
      <h1>File Library</h1>
    </div>
    <div class="view-content" v-if="!!files && files.length > 0 && !!filteredFiles">
      <div class="top">
        <div class="search-and-filter">
          <div class="search">
            <input type="text" title="Search Files" placeholder="Search" v-model="search" />
            <div class="icon-container">
              <i class="far fa-search"></i>
            </div>
          </div>
          <filter-dropdown class="dark" :options="filterOptions" option-label="name" option-key="value" v-model="selectedFilters" />
        </div>
      </div>
      <div class="dropzone-container">
        <vue-dropzone id="dropzone" ref="dropzone" :options="dropzoneOptions" :useCustomSlot="true" v-on:vdropzone-sending="onDropzoneSend">
          <div class="dropzone-custom-content">
            <div class="text">Drop files here to upload or</div>
            <div><a class="button">Select</a></div>
          </div>
        </vue-dropzone>
      </div>
      <div class="files-container" v-if="filteredFiles.length > 0">
        <div class="file" @click="selectedFile = file" v-for="file in filteredFiles">
          <div class="thumbnail" :style="`background-image: url('` + file.url + `');`" v-if="file.type === 'image' || file.type === 'video'"></div>
        </div>
      </div>
      <div class="no-matching-files" v-else>
        <div class="icon-container"><i class="far fa-exclamation-circle"></i></div>
        <div class="text">
          No files match your search and/or filter specification.
        </div>
      </div>
    </div>
    <div class="view-content" v-else>
      <div class="empty-state">
        <div class="icon-container"><i class="far fa-exclamation-circle"></i></div>
        <div class="text">
          You don't have any files yet.
        </div>
        <vue-dropzone id="empty_dropzone" ref="empty_dropzone" :options="dropzoneOptions" :useCustomSlot="true" v-on:vdropzone-sending="onDropzoneSend" v-on:vdropzone-success="onDropzoneSuccess">
          <div class="dropzone-custom-content">
            <div class="text">Drop files here to upload or</div>
            <div><a class="button">Select</a></div>
          </div>
        </vue-dropzone>
      </div>
    </div>
    <file-modal :file="selectedFile" @update-file="updateFile" @clickaway="fileIdToBeDeleted = selectedFile.id; selectedFile = null;" @delete="confirmDelete()" v-if="!!selectedFile"/>
    <modal
      v-if="showDiscardModal"
      header-text="Are you sure?"
      body-text="You're about to PERMANENTLY delete this file from Buildable. Do you really want to do this?"
      :buttons="buttons"
      class="dark"
      @closemodal="closeModal()"
    />
  </div>
</template>

<script>
  import { get, del } from '../helpers/api.js';
  import Modal from '../components/Modal';

  export default {
    components: [
      Modal
    ],
    data() {
      return {
        search: undefined,
        filterOptions: [
          { name: "Images", value: "image" },
          { name: "Videos", value: "video" },
          { name: "PDFs", value: "pdf" }
        ],
        selectedFilters: [ "image", "video", "pdf" ],
        dropzoneOptions: {
          url: '/api/buildable_files',
          paramName: 'uploaded_file',
          maxFilesize: 50,
          headers: { 'Authorization': 'Bearer '  + window.jwtToken }
        },
        files: null,
        selectedFile: null,
        fileIdToBeDeleted: null,

        showDiscardModal: false,

        buttons: [
            {
                text: "No",
                emitString: "closemodal",
                classes: "gray"
            },
            {
                text: "Yes",
                callback: this.discard
            }
        ],
      }
    },
    created() {
      this.initData();
    },
    computed: {
      filteredFiles() {
        const self = this;

        let returnArray = null;
        returnArray = this.files.filter( function(file) {
          let firstHalfOfMimeTypeMatches = self.selectedFilters.indexOf(file.type) > -1;
          let lastHalfOfMimeTypeMatches = self.selectedFilters.indexOf(file.mime_type.substring(file.mime_type.indexOf('/') + 1)) > -1;

          return firstHalfOfMimeTypeMatches || lastHalfOfMimeTypeMatches;
        });

        if (!!this.search) {
          returnArray = returnArray.filter( function(file) {
            return file.name.toLowerCase().indexOf(self.search.toLowerCase()) > -1;
          })
        }

        return returnArray;
      }
    },
    methods: {
      initData() {
        get('buildable_files', window.jwtToken)
          .then( (res) => {
            console.log(res);
            if (!!res && !!res.data && !!res.data.files) {
              this.files = res.data.files.map( function(file) {
                if (!!file.mime_type) {
                  file.type = file.mime_type.substring(0, file.mime_type.indexOf('/'));
                }
                return file;
              });
            }
          })
          .catch( (err) => {
            console.log(err);
          });
      },
      discard() {
          console.log("discarding..");
          this.fileUrl = this.originalUrl;
          this.fileName = this.originalName;
          this.fileCaption = this.originalCaption;

          this.fileIdToBeDeleted = this.selectedFile.id;

          del(`buildable_files/${this.fileIdToBeDeleted}`, window.jwtToken)
              .then( (res) => {
                  console.log("Success!");
                  this.showDiscardModal = false;
                  this.selectedFile = null;

                  this.initData();
              })
              .catch( (err) => err);
      },
      closeModal() {
        console.log("Inside closeModal()");

        this.showDiscardModal = false;
      },
      confirmDelete() {
          this.showDiscardModal = true;
      },
      onDropzoneSend(file, xhr, formData) {
        formData.append('metas', []);
      },
      onDropzoneSuccess(file, response) {
        this.initData();
      },
      updateFile(data) {
        if (data.prop !== "caption") {
          this.selectedFile[data.prop] = data.value;
        }
        else {
          const captionMetaIndex = this.selectedFile.metas.findIndex( function(meta) {
            return meta.key === "caption";
          });
          if (captionMetaIndex > -1) {
            this.selectedFile.metas[captionMetaIndex].value = data.value;
          }
          else {
            this.selectedFile.metas.push({ key: "caption", value: data.value });
          }
        }
      }
    }
  }
</script>
