<template>
  <div id="upload">
    <div class="message" v-if="message !== null">
      <div class="from" v-if="message.name !== null">{{ $t('messageFrom', { owner: message.name }) }}</div>
      <div v-html="message.message"></div>
    </div>

    <div class="uploadDisclaimer" v-if="$t('uploadDisclaimer')">
      {{ $t('uploadDisclaimer') }}
    </div>

    <div class="expirationDate" v-if="showExpirationNotice()">
      {{ getExpirationNotice() }}
    </div>


    <div class="uploadTarget"></div>

    <div class="navigation">
      <router-link to="/" class="pure-button">Terug</router-link>
    </div>
  </div>
</template>

<script>
import map from 'lodash/map';
import shared from '../shared';
import Uppy from '@uppy/core';
import Dashboard from '@uppy/dashboard';
import Tus from '@uppy/tus';
import axios from 'axios';

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

  data () {
    return {
      uploadToken: shared.uploadToken,
      message: null,
      expirationDate: null,
      expiration: null
    }
  },

  created()
  {
    var self = this;

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

      return;
    }


    axios.get('/info/' + encodeURIComponent(self.codeParam))
      .then((response) =>
      {
        self.message = response.data.message;
        self.expirationDate = response.data.expirationDate !== null ? new Date(response.data.expirationDate) : null;
        self.expiration = response.data.expiration;
      });
  },

  mounted()
  {
    var self = this;

    self.uppy = Uppy({
      id: 'userUpload',
      autoProceed: false,
      debug: true
    })
      .use(Dashboard, {
        inline: true,
        target: '.uploadTarget',
        replaceTargetContent: true
      })
      .use(Tus, {
        endpoint: '/upload/',
        headers: {
          Authorization: 'Bearer ' + self.uploadToken
        }
      })
      .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.uploadToken
        }
      })
      .then((response) =>
      {
        // TODO anything?
      })
      .catch((error) =>
      {
        // TODO can we convince Uppy that the files actually failed?
        shared.$emit('showNotification', error.message);
      });
    });

    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
      })
    });
  },


  methods: {
    showExpirationNotice()
    {
      var self = this;

      if (self.expirationDate != null)
        return self.$i18n.t('expirationNotice.date') != '';

      if (self.expiration != null)
        return self.$i18n.t('expirationNotice.timespan') != '';

      return self.$i18n.t('expirationNotice.never') != '';
    },


    getExpirationNotice()
    {
      var self = this;

      if (self.expirationDate != null)
        return self.$i18n.t('expirationNotice.date', {
          date: self.$options.filters.formatDate(self.expirationDate),
          time: self.$options.filters.formatTime(self.expirationDate)
        });

      if (self.expiration != null)
        return self.$i18n.t('expirationNotice.timespan',  {
          expiration: self.$tc('expirationValues.' + self.expiration.units,
                        self.expiration.value,
                        { count: self.expiration.value })
        });

      return self.$i18n.t('expirationNotice.never');
    }
  }
}
</script>

<style lang="scss">
.message
{
  .from
  {
    color: #808080;
    font-style: italic;
  }

  border-bottom: solid 1px #e0e0e0;
  margin-bottom: 1rem;
}


.navigation
{
  margin-top: 1rem;
  text-align: center;
}

.uploadDisclaimer, .expirationDate
{
  color: #808080;
  font-size: 75%;

  margin-bottom: 1rem;
}
</style>