<template>
  <div>
    <div :class="'form-group micro-attachment micro-attachment-size-' + imageSize">
      <label v-if="!!caption" :for="`inputAttachment${_uid}`">{{ caption }}</label>
      
      <div class="file-upload" :id="`fileUploadZone${_uid}`" v-show="backendUrl != noBackendUrl && !disabled">
        <slot name="button">
          <i class='mdi mdi-upload'></i> 
          {{ uploadText || `Drag and drop or choose a file to upload` }}
          <span v-show="maxAttachments">({{ maxAttachments }} max)</span>
        </slot>
      </div>

      <div class="file-list-container" v-show="docs.length">
        <ul>
          <draggable :id="`attachmentFiles${_uid}`" class="dragArea" :list="docs" v-bind="getOptions()">
            <li class="image-container" v-for="(file, index) in docs" :key="'file' + index">
              <div class="file-controls" v-show="backendUrl != noBackendUrl">
                <a class="remove-attachment" :href="includeToken(file.url)" target="_blank">
                  <span class="mdi mdi-download"></span>
                </a>
                <a href="javascript:;" class="remove-attachment" v-if="!disabled" @click="removeDocument(index)"><span class="mdi mdi-delete"></span></a>
              </div>

              <span class="mdi mdi-file-image" v-if="file.url && ! isImage(file.url)"></span>
              <img class="subject-image" :src="includeToken(file.url, { resize: imgResize })" v-if="file.url && isImage(file.url)" />

              <div class="file-name" v-show="(file.name || file.description) && showFileNames" :title="file.name">
                {{ file.name }}
                <span v-show="file.description">{{ file.description }}</span>
              </div>
            </li>
          </draggable>
        </ul>
      </div>

      <small class="form-text text-muted" v-show="description">
        {{ description }}
      </small>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import dropzone from 'dropzone'

export default {
  props: { 
    'caption': String, 
    'value': [String, Number, Object, Array], 
    'description': String,
    'uploadText': String,
    'maxAttachments' : {
      type: Number,
      default: 0
    },
    'maxSize' : {
      type: Number,
      default: 0
    },
    'allowedExtensions' : {
      type: Array,
      default: () => {
        return []
      }
    },
    'imageSize': {
      type: String,
      default: '100px'
    },
    'disabled': {
      type: Boolean,
      default: false
    },
    'showFileNames': {
      type: Boolean,
      default: true
    },
    'imgResize': {
      type: Boolean,
      default: false
    },
  },

  components: {
    draggable,
  },

  data() {
    return {
      noBackendUrl: 'localhost://',
      dropzoneObject: false,
      docs: [],
    }
  },

  beforeDestroy () {
    const vm = this

    if (vm.dropzoneObject) {
      vm.dropzoneObject.disable()
    }

    // Cleanup dropzone
    // $('.dz-hidden-input').remove()
    document.getElementsByClassName('dz-hidden-input').forEach((el) => {
      el.remove()
    })
  },

  mounted () {
    const vm = this

    if (vm.backendUrl != vm.noBackendUrl) {
      vm.dropzoneObject = new dropzone('#fileUploadZone' + vm._uid, {
        url: vm.backendUrl,
        complete: (file) => {
          var ret = JSON.parse(file.xhr.response)

          if (ret.error && ret.error.message) {
            vm.$emit('error', ret.error.message)
          } else {
            if (vm.maxAttachments && vm.docs.length >= vm.maxAttachments) {
              vm.$emit('error', `This field has a maximum number of ${vm.maxAttachments} attachments`)
              return
            }

            if (vm.maxSize && ret.result.size >= vm.maxSize * 1024) {
              vm.$emit('error', `This field has a maximum file size of ${vm.maxSize} kb`)
              return
            }

            if (vm.allowedExtensions.length) {
              if (ret.result.extension && vm.allowedExtensions.indexOf(ret.result.extension.toLowerCase()) == -1) {
                let ext = vm.allowedExtensions.join(', ')
                vm.$emit('error', `Only ${ext} file extensions are allowed`)
                return
              }
            }

            if(ret.error) {
              vm.$emit('error', ret.error);
            }
            else {
              vm.$emit('input',[...vm.docs, ret.result]);
            }
          }
        }
      })
    }

    if (vm.value && vm.value[0]) {
      vm.value.forEach(i => {
        if (i && i.url) {
          vm.docs.push(i)
        }
      })
    }
  },

  methods: {
    includeToken (value, options) {
      const vm = this
      if (vm.backendUrl != vm.noBackendUrl) {
        return (window.backendZero || window.backendPreviolet).storage().includeToken(value, options)
      } else {
        return value
      }
    },

    getOptions () {
      return { group: 'files' }
    },

    isImage (url) {
      url = url.toLowerCase()
      return url.indexOf('.png') != -1 || url.indexOf('.jpg') != -1 || url.indexOf('.jpeg') != -1 || url.indexOf('.gif') != -1
    },

    removeDocument(index) {
      this.docs.splice(index, 1)
      this.$emit('input', this.docs);
    }
  },

  computed: {
    backendUrl () {
      const vm = this
      let url = vm.noBackendUrl

      if (window.backendZero || window.backendPreviolet) {
        url = (window.backendZero || window.backendPreviolet).storage().getUploadUrl()
      }

      return url
    }
  },

  watch: {
    'value': function (newList) {
      this.docs = newList;
    }
  }
}
</script>

<style lang="scss">
.micro-attachment {
  .file-upload {
    border: solid 1px rgba(0, 0, 0, .1);
    border-radius: 4px;
    padding: 7px;
    text-align: center;
    color: #00000077;
    cursor: pointer;

    &:hover {
      color: #000000aa;
    }

    .dz-preview {
      display: none !important;
    }
  }

  .file-list-container {
    height: calc(100% - 75px);
    overflow: auto;

    ul {
      list-style: none;
      margin: 0;
      padding: 0;
      margin-left: -10px;

      li.image-container {
        background: #f7f7f7;
        border-radius: 4px;
        width: 100px;
        height: 100px;
        float: left;
        overflow: hidden;
        margin-left: 10px;
        margin-top: 10px;
        line-height: 12px;
        padding: 5px;
        position: relative;
        text-align: center;

        .mdi-file-image {
          font-size: 3em;
          display: block;
          width: 50%;
        }

        .file-name {
          position: absolute;
          font-size: .75em;
          background: rgba(0, 0, 0, .5);
          padding: 2px 5px;
          border-radius: 4px;
          color: #fff;
          bottom: 10px;
          white-space: nowrap;
          max-width: calc(100% - 20px);
          white-space: nowrap; ///garanteaza ca textul nu se intinde pe mai multe linii
          overflow: hidden; ///ascunde textul daca depaseste dimensiunea
          text-overflow: ellipsis; /// adauga ...
        }

        img {
          display: block;
          width: 100%;
          margin-bottom: 5px;
          border-radius: 3px;
        }

        .file-controls {
          font-size: 1.1em;
          position: absolute;
          border-radius: 4px;
          right: 3px;
          top: 3px;
          background: rgba(0, 0, 0, .5);
          padding: 3px;

          a {
            opacity: .7;
            margin: 0px 0px;
          }

          a:hover {
            opacity: 1;
          }

          a.remove-attachment {
            color: #fff;
          }
        }
      }
    }

    ul::after {
      content: "";
      clear: both;
      display: table;
    }
  }
}

.micro-attachment-size-100w {
  li.image-container {
    width: calc(100% - 10px) !important;
    height: calc(100% - 10px) !important;
  }
}

.micro-attachment-size-130px {
  li.image-container {
    width: 130px !important;
    height: 130px !important;
  }
}

.micro-attachment-size-200px {
  li.image-container {
    width: 200px !important;
    height: 200px !important;
  }
}
</style>
