<template>
  <div id="upload">
    <router-link to="/">Terug</router-link>
    <div class="uploadTarget"></div>
  </div>
</template>

<script>
import _ from 'lodash';
import shared from '../shared';
import Uppy from 'uppy/lib/core';
import Dashboard from 'uppy/lib/plugins/Dashboard';
import Tus from 'uppy/lib/plugins/Tus';
import axios from 'axios';

export default {
  props: [
    'codeParam',
    'i18n'
  ],

  data () {
    return {
      token: shared.token
    }
  },

  created()
  {
    var self = this;

    if (!self.token)
    {
      if (self.codeParam)
        self.$router.push('/c/' + self.codeParam);
      else
        self.$router.push('/c/');

      return;
    }
  },

  mounted()
  {
    var self = this;

    self.uppy = Uppy({
      id: 'userUpload',
      autoProceed: false,
      debug: true
    })
      .use(Dashboard, {
        inline: true,
        target: '.uploadTarget',
        replaceTargetContent: true,
        locale: {
          strings: {
            done: self.$i18n.t('uppyDashboard.done'),
            dropPaste: self.$i18n.t('uppyDashboard.dropPaste'),
            browse: self.$i18n.t('uppyDashboard.browse')
          }
        }
      })
      .use(Tus, {
        endpoint: '/upload/',
        headers: {
          Authorization: 'Bearer ' + self.token
        }
      })
      .run();

    self.uppy.on('complete', (result) =>
    {
      axios.post('/complete', {
        files: _.map(result.successful, (file) =>
        {
          return {
            id: file.tus.uploadUrl.substr(file.tus.uploadUrl.lastIndexOf('/') + 1),
            name: file.name
          };
        })
      },
      {
        headers: {
          Authorization: 'Bearer ' + self.token
        }
      })
      .then((response) =>
      {
        // TODO anything?
      })
      .catch((error) =>
      {
        // TODO can we convince Uppy that the files actually failed?
      });
    });

    self.uppy.on('upload-success', (file, resp, uploadURL) => {
      // Clear the uploadURL so the dashboard will not display it as a link.
      // The file can't be viewed by the user anyways since JWT headers are required.
      self.uppy.setFileState(file.id, {
        uploadURL: false
      })
    });
  }
}
</script>