const Cruises = require('../models/cruise');
const EventEmitter = require('events');
const Express = require('express');
const ParamStr = '/:limit?/:skip?/:locale?/:distance?';
const Router = Express.Router();
const Token = require('../modules/token');

function processQueryParams (params) {
  var query = {};
  
  if (params.locale) {
    var geo = {}; // geocode locale
    query['location.loc'] = { $near: geo };
  }
  
  return query;
}

function update (req, res, next) {
  Token.verifyThen(req.get('authorization'), 'update', (err, decoded) => {
    if (err || (decoded && !decoded.hasPermission)) {
      res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
      return;
    } 
    
    if (decoded && decoded.hasPermission) {
      var CruiseEvents = new EventEmitter();  
      var id = req.params.id;
      var data = req.body;
    
      if (!id || !data) {
        res.status(500).json({ message: 'No cruise id or data specified.', err: err });
        return;
      }

      CruiseEvents.once('update', (err, result) => {
        if (err) {
          res.status(500).json({message: 'Could not update cruise id: ' + id, err: err});
        }

        if (result) {
          res.status(200).json(result);
        }
      });

      Cruises.update(CruiseEvents, id, data);
    }
  });
}

Router.route('/find' + ParamStr)
  .get((req, res) => {
    Token.verifyThen(req.get('authorization'), 'view', (err, decoded) => {
      if (err || (decoded && !decoded.hasPermission)) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
    
      if (decoded && decoded.hasPermission) {
        var CruiseEvents = new EventEmitter();
        var find = processQueryParams(req.params);

        var query = {
          find: find,
          select: null,
          options: {
            limit: !isNaN(parseInt(req.params.limit)) ? parseInt(req.params.limit) : 0,
            skip: !isNaN(parseInt(req.params.skip)) ? parseInt(req.params.skip) : 0,
            sort: { 'order': 1 }
          }
        };		
  
        CruiseEvents.once('find', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'There was an error getting the getting the cruises [' + err + ']', err: err });
          }
  
          if (result) {
            res.status(200).json(result);
          }		
        });

        Cruises.find(CruiseEvents, query);
      }
    });
  });

Router.route('/list' + ParamStr)
  .get((req, res) => {
    Token.verifyThen(req.get('authorization'), 'view', (err, decoded) => {
      if (err || (decoded && !decoded.hasPermission)) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
    
      if (decoded && decoded.hasPermission) {
        var CruiseEvents = new EventEmitter();
        var find = processQueryParams(req.params);

        var query = {
          find: find,
          select: { order: 1, 'details.name': 1, 'details.pic.thumb': 1 },
          options: {
            limit: (!isNaN(parseInt(req.params.limit)) ? parseInt(req.params.limit) : 0),
            skip: (!isNaN(parseInt(req.params.skip)) ? parseInt(req.params.skip) : 0),
            sort: { 'order': 1 }
          }
        };		
  
        CruiseEvents.once('find', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'There was an error getting the cruise list [' + err + ']', err: err });
          }
  
          if (result) {
            res.status(200).json(result);
          }		
        });

        Cruises.find(CruiseEvents, query);
      }
    });
  });

Router.route('/:id?')
	.delete( (req, res) => {
    Token.verifyThen(req.get('authorization'), 'delete', (err, decoded) => {
      if (err || (decoded && !decoded.hasPermission)) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
    
      if (decoded && decoded.hasPermission) {
        var CruiseEvents = new EventEmitter();  
        var id = req.params.id;

        CruiseEvents.once('delete', (err, result) => {
          if (err) {
            res.status(500).json({message: 'Could not delete cruise id: ' + id, err: err});
          }

          if (result) {
            res.status(204).json({});
          }
        });

        Cruises.delete(CruiseEvents, id);
      }
    });
	})
	.get( (req, res) => {
    Token.verifyThen(req.get('authorization'), 'view', (err, decoded) => {
      if (err || (decoded && !decoded.hasPermission)) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
    
      if (decoded && decoded.hasPermission) {
        var CruiseEvents = new EventEmitter();
        var id = req.params.id || null;
        var method = id ? 'get' : 'all';

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

        Cruises[method](CruiseEvents, id);
      }
    });
	})
	.patch( update )
  .post((req, res) => {
    Token.verifyThen(req.get('authorization'), 'add', (err, decoded) => {
      if (err || (decoded && !decoded.hasPermission)) {
        res.status(403).json({ message: 'User not authorized to perform this action.', err: err });
        return;
      } 
    
      if (decoded && decoded.hasPermission) {
        var CruiseEvents = new EventEmitter();
        var cruise = Array.isArray(req.body) ? req.body : [ req.body ];
        var multi = cruise.length > 1;

        CruiseEvents.once('create', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'Could not create cruise' + (multi ? 's' : ''), err: err, cruise: cruise });
          }

          if (result) {
            res.status(200).json(result);
          }
        });

        Cruises.create(CruiseEvents, cruise);
      }
    });
  })
	.put( update );

module.exports = Router;
