'use strict';
const { Router } = require('express');
const { getAllTests } = require('../db');

const router = Router();

router.get('/', (req, res) => {
  const { completed, interference, device, rotation, testPoint,
          station, band, channel, bandwidth, rssi, direction } = req.query;

  let tests = getAllTests();

  if (completed !== undefined)
    tests = tests.filter(t => t.completed === (completed === 'true' ? 1 : 0));
  if (interference) tests = tests.filter(t => t.interference === interference);
  if (device)       tests = tests.filter(t => t.device       === device);
  if (rotation)     tests = tests.filter(t => t.rotation     === rotation);
  if (testPoint)    tests = tests.filter(t => t.test_point   === testPoint);
  if (station)      tests = tests.filter(t => t.station      === station);
  if (band)         tests = tests.filter(t => t.band         === band);
  if (channel)      tests = tests.filter(t => t.channel      === channel);
  if (bandwidth)    tests = tests.filter(t => t.bandwidth    === bandwidth);
  if (rssi)         tests = tests.filter(t => t.rssi         === rssi);
  if (direction)    tests = tests.filter(t => t.direction    === direction);

  tests.sort((a, b) => {
    const ia = a.interference || '';
    const ib = b.interference || '';
    return ia.localeCompare(ib) || (a.test_id || '').localeCompare(b.test_id || '');
  });

  res.json(tests);
});

module.exports = router;

