const config = require('config');
const express = require('express');
const router = express.Router();

const originalEvents = require('../event-data.js');
const originalGroups = require('../group-data.js');

router.put('/', (req, res) => {
  const event = req.body;
  event.id = originalEvents.length;
  originalEvents.push(event);
  res.status(200).send([event]);
});

router.get('/google-api-key', (req, res) => {
  return res.status(200).send({ key: config.get('googleApi') });
});

router.get('/:event?', (req, res) => {
  const { event } = req.params;
  const { groupId } = req.query;

  if (!event) {
    return res.status(200).send(originalEvents);
  }

  const group = originalGroups.find(item => {
    return (item.groupId === groupId || item.group === groupId);
  });

  if (!group) {
    return res.status(500).send({ message: `Invalid group-event link.` });
  }

  const found = originalEvents.find((item) => {
    if (item.groupId !== group.id) {
      return false;
    }
    if (typeof event === 'number') {
      return item.id === event;
    }
    if (typeof event === 'string') {
      return item.event === event;
    }
    return false;
  });
  if (!found) {
    return res.status(404).send({ 
      message: `Unable to find ${groupId}:${event}.`
    });
  }
  return res.status(200).send([found]);
});

router.post('/:eventId', (req, res) => {
  const { eventId } = req.params;
  if (!eventId) {
    return res.status(400).send({ message: `Invalid event.` });
  }
  const event = originalEvents.find(
    item => item.id === eventId
  );
  if (!event) {
    res.status(404).send({ message: `Event ${eventId} not found.` });
  }
  res.status(200).send([event]);
});

router.delete('/:eventId', (req, res) => {
  const { eventId } = req.params;
  if (!eventId) {
    return res.status(400).send({ message: `Invalid event.` });
  }
  const eventIndex = originalEvents.findIndex(
    item => item.id === eventId
  );
  if (eventIndex === -1) {
    res.status(404).send({ message: `Event ${eventId} not found.` });
  }
  originalEvents.splice(eventIndex, 1);
  res.status(200).send({ message: `Event ${eventId} deleted.` });
});

module.exports = router;
