var EventEmitter = require('events');
var Express = require('express');
var GeocacheModel = require('../models/geocache');
var Router = Express.Router();
var Token = require('../modules/token');

function updateGeocache (req, res, next) {
  Token.verifyThen(req.get('authorization'), 'manageAppPreferences', (err, decoded) => {
    if (err) {
      res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
      return;
    } 
  
    var GeoEvents = new EventEmitter();
    var id = req.params.id;
    var data = req.body;

    GeoEvents.once('update', (err, result) => {
      if (err) {
        res.status(500).json({ message: 'Could not get geodata' + (id ? ' for id: ' + id : ''), err: err });
      }
    
      if (result) {
        res.status(200).json(result);
      }		
    });

    GeocacheModel.update(GeoEvents, id, geodata);
  });
}

Router.route('/populate/:field')
  .get((req, res, next) => {
    Token.verifyThen(req.get('authorization'), 'manageAppPreferences', (err, decoded) => {
      if (err) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
  
      var GeoEvents = new EventEmitter();
      var method = 'populate' + (req.params.field[0].toUpperCase() + req.params.field.substring(1));

      GeoEvents.once(method, (err, result) => {
        if (err) {
          res.status(500).json({ message: 'Could not get geodata' + (id ? ' for id: ' + id : ''), err: err });
        }
    
        if (result) {
          res.status(200).json(result);
        }		
      });

      GeocacheModel[method](GeoEvents);
    });
  });

Router.route('/:id?')
	.get((req, res, next) => {
    Token.verifyThen(req.get('authorization'), 'viewPublicDetails', (err, decoded) => {
      if (err) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
    
      var GeoEvents = new EventEmitter();
      var id = req.params.id || false;
      var method = id ? 'getGeo' : 'getGeos';

      GeoEvents.once(method, (err, result) => {
        if (err) {
          res.status(500).json({ message: 'Could not get geodata' + (id ? ' for id: ' + id : ''), err: err });
        }
      
        if (result) {
          res.status(200).json(result);
        }		
      });

      GeocacheModel[method](GeoEvents, id || null);
    });
	})
	.patch( updateGeocache )
	.post( updateGeocache )
	.put( updateGeocache );

module.exports = Router;
