<template>
  <div class="modal file_library-modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">
          <div class="modal-header">
            <h1>File Library</h1>
            <div class="text">Choose media</div>
            <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 @click="$emit('close')" class="icon-container close">
              <i class="far fa-times fa-fw"></i>
            </div>
          </div>
          <div class="modal-body">
            <div class="file-library-container" v-if="!!files && files.length > 0">
              <div class="files-container" v-if="filteredFiles.length > 0">
                <div class="file" :class="{ selected: (!!selectedIDs && selectedIDs.indexOf(file.id) > -1) }" @click="selectFile(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="empty-state" v-else>
              <div class="icon-container"><i class="far fa-exclamation-circle"></i></div>
              <div class="text">
                You don't have any files yet.
              </div>
            </div>
            <div class="dropzone-container">
              <vue-dropzone id="dropzone" ref="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>
          <div class="modal-footer">
            <div class="buttons-container">
              <a class="button dark-gray" @click="cancel">Cancel</a>
              <a class="button" @click="$emit('close')">Done</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { mixin as clickaway } from 'vue-clickaway2';
  import { get } from '../helpers/api.js';

  export default {
    mixins: [ clickaway ],
    props: [ "value", "multi", "images", "videos" ],
    data() {
      return {
        search: undefined,
        filterOptions: [],
        selectedFilters: [],
        allowMulti: this.multi === "",
        showImages: this.images === "",
        showVideos: this.videos === "",
        dropzoneOptions: {
          url: '/api/buildable_files',
          paramName: 'uploaded_file',
          maxFilesize: 50,
          headers: { 'Authorization': 'Bearer '  + window.jwtToken }
        },
        previousValue: this.value
      }
    },
    mounted() {
      if (!!this.showImages) {
        this.filterOptions.push({ name: "Images", value: "image" });
        this.selectedFilters.push("image");
      }
      if (!!this.showVideos) {
        this.filterOptions.push({ name: "Videos", value: "video" });
        this.selectedFilters.push("video");
      }
    },
    computed: {
      files() {
        return this.$store.state.storage.files;
      },
      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;
      },
      selected: {
        get() {
          return this.value;
        },
        set(val) {
          this.$emit('input', val);
        }
      },
      selectedIDs() {
        if (!!this.selected) {
          if (Array.isArray(this.selected)) {
            return this.selected.map( function(file) {
              return file.id;
            });
          }
          else {
            return [ this.selected.id ];
          }
        }
      }
    },
    methods: {
      onDropzoneSend(file, xhr, formData) {
        formData.append('metas', []);
      },
      onDropzoneSuccess(file, response) {
        this.$store.commit('getFiles');
        if (!!response && !!response.new_file) {
          this.selected = response.new_file;
        }
      },
      cancel() {
       this.selected = this.previousValue;
       this.$emit('close');
      },
      selectFile(file) {
        if (!!this.allowMulti) {
          let array = [];
          if (!!this.selected && !!Array.isArray(this.selected)) {
            array = _.cloneDeep(this.selected);
          }

          // See if the file is already in the array
          let fileInArray = array.find( function(f) {
            return f.id === file.id;
          });

          if (!fileInArray) {
            array.push(file);
          }
          else {
            array = array.filter( function(f) {
              return f.id !== file.id;
            });
          }

          this.selected = array;
        }
        else {
          if (!this.selected || this.selected.id !== file.id) {
            this.selected = file;
          }
          else {
            this.selected = null;
          }
        }
      }
    }
  }
</script>
