<template>
  <div id="uploads">
    <div v-if="uploads !== null" class="list">
      <div v-for="group in groupedUploads">
        <div class="properties">
          <div class="pure-g">
            <div class="pure-u-1-1"><span class="text codedescription">{{ group.lastUpload.codedescription || group.lastUpload.codeId }}</span></div>
            <div class="pure-u-1-3"><span class="text">{{ group.lastUpload.codeId }}</span></div>
            <div class="pure-u-1-3">
              <span class="text" v-if="hasAuth('viewAllUploads')" :class="{ userDeleted: !group.lastUpload.username }">
                {{ group.lastUpload.username || $t('admin.uploads.userDeleted') }}
              </span>
            </div>
            <div class="pure-u-1-3 right">
              <span class="text" v-if="group.lastUpload.expirationDate">{{ $t('admin.uploads.expiration') }} {{ group.lastUpload.expirationDate | formatDateTime }}</span>
            </div>
          </div>
        </div>

        <UploadFiles :group="group" v-bind:assignUsers="assignUsers" @files-deleted="onFilesDeleted" @code-assigned="onCodeAssigned"></UploadFiles>
      </div>

      <div v-if="uploads.length == 0" class="nodata">
        {{ $t('admin.empty') }}
      </div>
    </div>

    <div v-else class="loading">
      {{ $t('admin.loading') }}
    </div>
  </div>
</template>

<script>
import UploadFiles from './components/UploadFiles.vue';
import orderBy from 'lodash/orderBy';
import findIndex from 'lodash/findIndex';
import forEach from 'lodash/forEach';
import axios from 'axios';
import shared from '../../shared';

export default {
  components: {
    UploadFiles
  },

  data()
  {
    return {
      uploads: null,
      assignUsers: []
    };
  },

  created()
  {
    var self = this;

    if (!shared.adminToken)
    {
      self.$router.push('/admin');
      return;
    }


    axios.get('/admin/uploads', {
      headers: {
        Authorization: 'Bearer ' + shared.adminToken
      }
    })
    .then((response) =>
    {
      self.uploads = orderBy(response.data, ['created'], ['desc']);
    })
    .catch((error) => { shared.$emit('apiError', error, this.$router) });


    axios.get('/admin/assign/users', {
      headers: {
        Authorization: 'Bearer ' + shared.adminToken
      }
    })
    .then((response) =>
    {
      self.assignUsers = orderBy(response.data, ['name'], ['asc']);
    })
    .catch((error) => { shared.$emit('apiError', error, this.$router) });
  },


  computed: {
    groupedUploads()
    {
      let self = this;
      let codes = {};

      // Get unique codes and their highest upload time
      forEach(self.uploads, (upload) =>
      {
        if (!codes.hasOwnProperty(upload.codeId))
        {
          codes[upload.codeId] = {
            maxCreated: upload.created,
            uploads: [upload],
            lastUpload: upload
          };
        }
        else
          // uploads is sorted by created descending, so no need to update maxCreated
          codes[upload.codeId].uploads.push(upload);
      });

      return orderBy(codes, ['maxCreated'], ['desc']);
    }
  },


  methods: {
    hasAuth(token)
    {
      return shared.user !== null && shared.user.auth.indexOf(token) > -1;
    },


    onFilesDeleted(files)
    {
      var self = this;
      for (let i = self.uploads.length - 1; i >= 0; i--)
      {
        let upload = self.uploads[i];

        for (let f = upload.files.length - 1; f >= 0; f--)
        {
          if (findIndex(files, { uploadId: upload.id, fileId: upload.files[f].id }) > -1)
          {
            upload.files.splice(f, 1);
          }
        }

        if (upload.files.length == 0)
          self.uploads.splice(i, 1);
      }
    },


    onCodeAssigned(codeId, userId)
    {
      var self = this;
      if (self.hasAuth('viewAllUploads'))
      {
        let username = null;
        forEach(self.assignUsers, (user) =>
        {
          if (user.id == userId)
            username = user.name;
        })

        self.updateCodeUser(codeId, userId, username);
      }
      else
        self.removeCodeUploads(codeId);
    },


    removeCodeUploads(codeId)
    {
      var self = this;

      for (let i = self.uploads.length - 1; i >= 0; i--)
      {
        if (self.uploads[i].codeId == codeId)
          self.uploads.splice(i, 1);
      }
    },


    updateCodeUser(codeId, userId, username)
    {
      var self = this;

      forEach(self.uploads, (upload) =>
      {
        if (upload.codeId == codeId)
        {
          upload.userId = userId;
          upload.username = username;
        }
      });
    }
  }
}
</script>

<style lang="scss">
.right
{
  text-align: right;
}


.properties
{
  background-color: #f4f4f4;
  padding: .2rem;
}
</style>