const asyncHandler = require('express-async-handler');
const AuthTokens = require('../../authtokens');
const resolvePath = require('resolve-path');
const groupBy = require('lodash/groupBy');
const map = require('lodash/map');


module.exports = (repository, router) =>
{
  router.get('/uploads', asyncHandler(async (req, res) =>
  {
    var files = await repository.uploads.list(req.user.hasAuth(AuthTokens.ViewAllUploads) ? null : req.user.id);
    var usernames = await repository.users.getNames();
    var codedescriptions = await repository.codes.getDescriptions();

    files.forEach((item) =>
    {
      item.username = item.userId !== null ? usernames[item.userId] : null;
      item.codedescription = item.codeId !== null ? codedescriptions[item.codeId] : null;
    });

    res.send(files);
  }));


  router.delete('/uploads/:id', asyncHandler(async (req, res) =>
  {
    var upload = await repository.uploads.get(req.params.id);
    if (upload == null || (upload.userId !== req.user.id && !req.user.hasAuth(AuthTokens.ViewAllUploads)))
    {
      res.sendStatus(404);
      return;
    }

    await repository.uploads.delete(upload.id);
    res.sendStatus(200);
  }));


  router.delete('/fileuploads/', asyncHandler(async (req, res) =>
  {
    var groupedFiles = groupBy(req.body, (value) => value.uploadId);

    for (var uploadId in groupedFiles)
    {
      await repository.uploads.deleteFiles(uploadId,
        map(groupedFiles[uploadId], (file) => { return file.fileId }));
    }

    res.sendStatus(200);
  }));


  router.delete('/codeuploads/:code', asyncHandler(async (req, res) =>
  {
    var uploads = await repository.uploads.listForCode(req.params.code);
    if (uploads === null)
    {
      res.sendStatus(404);
      return;
    }

    if (!req.user.hasAuth(AuthTokens.ViewAllUploads))
    {
      for (let i = 0; i < uploads.length; i++)
      {
        if (uploads[i].userId !== req.user.id)
        {
          res.sendStatus(404);
          return;
        }
      }
    }

    for (let i = 0; i < uploads.length; i++)
      await repository.uploads.delete(uploads[i].id);

    res.sendStatus(200);
  }));


  router.get('/download/:fileid/:displayname', asyncHandler(async (req, res) =>
  {
    // TODO should we check if the user has access to the file?
    // for now not that important, if you know the file's UID and are logged in

    var fullpath = resolvePath(config.fileUpload.path, req.params.fileid);
    res.download(fullpath, req.params.displayname);
  }));
}