<script>
import ajax from './ajax';
import UploadDragger from './upload-dragger.vue';

const errorType = {
  LIMIT: 'limit',
  SIZE: 'size',
  FORMAT: 'format'
};

const validateFileFormat = (file, acceptParam) => {
  const accept = (acceptParam || '').trim();
  if (!accept) return true;

  // remove whitespace, split by commas and replace * with .* so it could be fed to the RegExp constructor with the i flag set
  const acceptRegexChunks = accept.replace(/\s/g, '').split(',').map(chunk => new RegExp(chunk.replace('*', '.\*'), 'i'));

  // check if it matches one or more allowed file types
  return acceptRegexChunks.filter(regexChunk => regexChunk.test(file.type)).length > 0;
};

const validateFileSize = (file, maxSizeInKiloBytes) => {
  const maxSizeInBytes = maxSizeInKiloBytes * 1024;
  return file.size <= maxSizeInBytes;
};

export default {
  inject: ['uploader'],
  components: {
    UploadDragger
  },
  props: {
    type: String,
    action: {
      type: String,
      required: true
    },
    method: {
      type: String,
      required: true
    },
    name: {
      type: String,
      default: 'file'
    },
    fileKey: {
      type: String,
      default: 'file'
    },
    maxFileSize: Number,
    data: Object,
    headers: Object,
    withCredentials: Boolean,
    multiple: Boolean,
    accept: String,
    onStart: Function,
    onProgress: Function,
    onSuccess: Function,
    onError: Function,
    beforeUpload: Function,
    beforeRequest: {
      type: Function,
      default: () => () => {}
    },
    drag: Boolean,
    onPreview: {
      type: Function,
      default: function() {}
    },
    onRemove: {
      type: Function,
      default: function() {}
    },
    fileList: Array,
    listPlacement: String,
    autoUpload: Boolean,
    listType: String,
    httpRequest: {
      type: Function,
      default: ajax
    },
    disabled: Boolean,
    limit: Number,
    onSelectError: Function,
    expanded: Boolean,
    dropzoneStyle: Object,
    dropzoneClass: String
  },

  data() {
    return {
      mouseover: false,
      reqs: {}
    };
  },

  methods: {
    isImage(str) {
      return str.indexOf('image') !== -1;
    },
    handleChange(ev) {
      const files = ev.target.files;

      if (!files) return;
      this.uploadFiles(files);
    },
    uploadFiles(files) {
      // validate limit
      if (this.multiple) {
        if (this.limit && (this.fileList.length + files.length) > this.limit) {
          this.onSelectError(files, files, this.fileList, errorType.LIMIT);
          return;
        }
      } else if (files.length > 1) {
        // when `multiple` attribute isn't set on file inputs, browsers don't allow users
        // to select more than one file using file explorer.
        // this will only be triggered when `multiple` isn't set and `drag` is set and user
        // tries to drag more than one files into the dropzone.
        this.onSelectError(files, files, this.fileList, errorType.LIMIT);
        return;
      }

      let postFiles = Array.prototype.slice.call(files);
      if (!this.multiple) { postFiles = postFiles.slice(0, 1); }

      if (postFiles.length === 0) { return; }

      // validate format
      let unsupportedFiles = postFiles.filter(rawFile => !validateFileFormat(rawFile, this.accept));
      if (unsupportedFiles.length) {
        this.onSelectError(unsupportedFiles, files, this.fileList, errorType.FORMAT);
        return;
      }

      // validate size
      unsupportedFiles = postFiles.filter(rawFile => !validateFileSize(rawFile, this.maxFileSize));
      if (unsupportedFiles.length) {
        this.onSelectError(unsupportedFiles, files, this.fileList, errorType.SIZE);
        return;
      }

      postFiles.forEach(rawFile => {
        this.onStart(rawFile);
        if (this.autoUpload) this.upload(rawFile);
      });
    },
    upload(rawFile) {
      this.$refs.input.value = null;

      if (!this.beforeUpload) {
        return this.post(rawFile);
      }

      const before = this.beforeUpload(rawFile);
      if (before && before.then) {
        before.then(processedFile => {
          const fileType = Object.prototype.toString.call(processedFile);

          if (fileType === '[object File]' || fileType === '[object Blob]') {
            if (fileType === '[object Blob]') {
              processedFile = new File([processedFile], rawFile.name, {
                type: rawFile.type
              });
            }
            for (const p in rawFile) {
              if (rawFile.hasOwnProperty(p)) {
                processedFile[p] = rawFile[p];
              }
            }
            this.post(processedFile);
          } else {
            this.post(rawFile);
          }
        }, () => {
          this.onRemove(null, rawFile);
        });
      } else if (before !== false) {
        this.post(rawFile);
      } else {
        this.onRemove(null, rawFile);
      }
    },
    abort(file) {
      const { reqs } = this;
      if (file) {
        let uid = file;
        if (file.uid) uid = file.uid;
        if (reqs[uid]) {
          reqs[uid].abort();
        }
      } else {
        Object.keys(reqs).forEach((uid) => {
          if (reqs[uid]) reqs[uid].abort();
          delete reqs[uid];
        });
      }
    },
    post(rawFile) {
      const { uid } = rawFile;

      const requestParameters = this.beforeRequest(rawFile) || {};

      const options = {
        method: this.method,
        headers: this.headers,
        withCredentials: this.withCredentials,
        file: rawFile,
        data: Object.assign({}, this.data, requestParameters),
        fileKey: this.fileKey,
        action: this.action,
        onProgress: e => {
          this.onProgress(e, rawFile);
        },
        onSuccess: res => {
          this.onSuccess(res, rawFile);
          delete this.reqs[uid];
        },
        onError: err => {
          this.onError(err, rawFile);
          delete this.reqs[uid];
        }
      };
      const req = this.httpRequest(options);
      this.reqs[uid] = req;
      if (req && req.then) {
        req.then(options.onSuccess, options.onError);
      }
    },
    handleClick() {
      if (!this.disabled) {
        this.$refs.input.value = null;
        this.$refs.input.click();
      }
    },
    handleKeydown(e) {
      if (e.target !== e.currentTarget) return;
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.handleClick();
      }
    }
  },

  render(h) {
    let {
      handleClick,
      drag,
      name,
      handleChange,
      multiple,
      accept,
      listType,
      listPlacement,
      uploadFiles,
      disabled,
      handleKeydown,
      expanded,
      dropzoneStyle,
      dropzoneClass
    } = this;
    const data = {
      class: {
        'el-upload': true,
        'u-block': expanded
      },
      on: {
        click: handleClick,
        keydown: handleKeydown
      }
    };
    data.class[`el-upload--${listType}`] = listPlacement === 'default';
    return (
      <div {...data} tabindex="0" >
        {
          drag
            ? <upload-dragger style={dropzoneStyle} class={{ 'u-width100': expanded, [dropzoneClass]: true }} disabled={disabled} on-file={uploadFiles}>{this.$slots.default}</upload-dragger>
            : this.$slots.default
        }
        <input class="el-upload__input" type="file" ref="input" name={name} on-change={handleChange} multiple={multiple} accept={accept}></input>
      </div>
    );
  }
};
</script>
