const Test = require('../models').models.Test;
const Hardware = require('../models').models.Hardware;
const Benchmark = require('../models').models.Benchmark;

// GET /test - redirects to test list
exports.getIndex = async function(req, res) {
  res.redirect('/test/list');
};

// GET /test/list - list of tests
exports.getList = async function(req, res) {
  var tests = await Test.findAll({order: [['updatedAt', 'DESC']]});
  res.render('test/list', {
    tests: tests
  });
};

// GET /test/:test_id - view information about a test
exports.getView = async function(req, res) {
  var test = await Test.findAll({
    where: {
      id: req.params.test_id
    }
  });
  res.render('test/view', {
    test: test[0]
  });
};

// GET /test/add - add a new test
exports.getAdd = async function(req, res) {
  var hardware = await Hardware.findAll();
  var benchmarks = await Benchmark.findAll();

  res.render('test/add', {
    hardware: hardware,
    benchmarks: benchmarks
  });
};

// POST /test/add - add the test to the database
exports.postAdd = async function(req, res) {
  var test = await Test.create({
    title: req.body.test_title,
    description: req.body.test_description,
  });

  // add link to hardware
  let hardware = await Hardware.findByPk(req.body.test_hardware);
  test.setHardware(hardware);

  // add links to benchmarks
  for (let b = 0; b < req.body.test_benchmarks.length; b++) {
    let benchmark = await Benchmark.findByPk(req.body.test_benchmarks[b]);
    test.addBenchmark(benchmark);
  }

  res.redirect('/test/' + test.id);
};
