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

const originalLocations = require('../location-data.js');

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

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

router.get('/:locationId?', (req, res) => {
  const { locationId } = req.params;
  if (locationId) {
    const location = originalLocations.find(
      item => item.id === locationId
    );
    if (!location) {
      return res.status(404).send({ message: `Location ${locationId} not found.`});
    }
    return res.status(200).send([ location ]);
  }

  return res.status(200).send(originalLocations);
});

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

router.delete('/:locationId', (req, res) => {
  const { locationId } = req.params;
  if (!locationId) {
    return res.status(400).send({ message: `Invalid location.` });
  }
  const locationIndex = originalLocations.findIndex(
    item => item.id === locationId
  );
  if (locationIndex === -1) {
    res.status(404).send({ message: `Location ${locationId} not found.` });
  }
  originalLocations.splice(locationIndex, 1);
  res.status(200).send({ message: `Location ${locationId} deleted.`});
});

module.exports = router;
