<template>
  <div class="file-upload"
       :class="{'file-upload--dropzone': dropzone}">
    <file-upload-container
      :type="type"
      :fileTypes="fileTypes"
      :dropzone="dropzone"
      :button-title="buttonTitle"
      @upload="uploadFile"
    >
      <file-upload-list
        v-if="files.length"
        :type="type"
        :files="files"
        @remove="removeFile"
        @remove-single="removeSingleFile"
      />

      <template #custom-actions>
        <slot></slot>
      </template>

    </file-upload-container>
  </div>
</template>

<script>
import FileUploadList from './FileUploadList'
import FileUploadContainer from './FileUploadContainer'

export default {
  name: 'file-upload',
  components: {
    FileUploadList: FileUploadList,
    FileUploadContainer: FileUploadContainer,
  },
  props: {
    type: {
      type: String,
      default: 'list',
      validator: function (value) {
        return ['list', 'gallery', 'single'].indexOf(value) !== -1
      },
    },
    fileTypes: {
      type: String,
      default: '',
    },
    dropzone: {
      type: Boolean,
      default: false,
    },
    buttonTitle: {
      type: String
    },
    value: {
      default: () => [],
    },
  },
  methods: {
    uploadFile (e) {
      let files = e.target.files || e.dataTransfer.files

      // type validation
      if (this.fileTypes) {
        files = this.validateFileTypes(files)
      }
      this.files = [...this.files, ...files]
    },
    removeFile (index) {
      this.files.splice(index, 1)
    },
    removeSingleFile () {
      this.files = []
    },
    validateFileTypes (files) {
      return [...files].filter(file => {
        const fileName = file.name
        const extn = fileName.substring(fileName.lastIndexOf('.') + 1)
          .toLowerCase()
        if (this.fileTypes.indexOf(extn) === -1) {
          alert("File type is incorrect...");
        }
        return this.fileTypes.indexOf(extn) !== -1
      })
    },
  },
  computed: {
    files: {
      get () {
        return this.value
      },
      set (files) {
        this.$emit('input', files)
      },
    },
  },
}
</script>

<style lang='scss'>
.file-upload {
  &--dropzone {
    background-color: #e9fde8;
    padding: 0 2rem;
    overflow: hidden;
  }
}

.btn-text {
  border: none;
  background: none;
  outline: none;
  cursor: pointer;
  padding: 0;

  & + & {
    margin-left: 1.5rem;
  }

  &--primary {
    color: #4ae387;

    &:hover {
      opacity: 0.6;
    }
  }

  &--secondary {
    color: #ffffff;
  }
}

@media (max-width: 576px) {
  .file-upload {
    &--dropzone {
      padding: 0 1rem;
    }
  }
}
</style>
