const config = require('../../config');
const express = require('Express');
const asyncHandler = require('express-async-handler');
const jwt = require('jsonwebtoken');


async function checkAuthorization(req, res, onVerified)
{
  if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer')
  {
    res.sendStatus(400);
    return;
  }

  var token = req.headers.authorization.split(' ')[1];
  jwt.verify(token, config.jwtSecret, async (err, decoded) =>
  {
    try
    {
      if (err)
      {
        res.sendStatus(403);
        return;
      }

      if (decoded.userId)
        await onVerified(decoded);
      else
        res.sendStatus(400);
    }
    catch (e)
    {
      console.log(e);
      res.sendStatus(500);
    }
  });
}



module.exports = (repository) =>
{
  var router = express.Router();

  router.get('/codes', asyncHandler(async (req, res) =>
  {
    await checkAuthorization(req, res, async (decoded) =>
    {
      var codes = await repository.codes.getCodes(decoded.userId);
      var usernames = await repository.users.getUsernames();

      codes.forEach((item) =>
      {
        item.username = usernames[item.userId];
      });

      res.send(codes);
    });
  }));


  router.get('/uploads', asyncHandler(async (req, res) =>
  {
    await checkAuthorization(req, res, async (decoded) =>
    {
      var files = await repository.uploads.getUploads(decoded.userId);
      var usernames = await repository.users.getUsernames();

      files.forEach((item) =>
      {
        item.username = usernames[item.userId];
      });

      res.send(files);
    });
  }));


  return router;
}