const EventEmitter = require('events');
const Express = require('express');
const ParamStr = '/:limit?/:skip?/:min?/:max?/:pos?/:lkng?/:tribes?/:ethnos?';
const Profiles = require('../models/profile');
const Router = Express.Router();
const Token = require('../modules/token');

function processQueryParams (params) {
  var query = {};
  
  if (params.min && !isNaN(parseInt(params.min))) {
    query['details.age'] = query['details.age'] || {};
    query['details.age'].$gte = parseInt(params.min);
  }
  
  if (params.max && !isNaN(parseInt(params.max))) {
    query['details.age'] = query['details.age'] || {};
    query['details.age'].$lte = parseInt(params.max);
  }
  
  if (params.pos && params.pos !== 'null') {
    query['details.position'] = { $in: params.pos.split('|') };
  }
  
  if (params.lkng && params.lkng !== 'null') {
    query['details.looking'] = { $in: params.lkng.split('|') };
  }
  
  if (params.tribes && params.tribes !== 'null') {
    query['details.tribes'] = { $in: params.tribes.split('|') };
  }
  
  if (params.ethnos && params.ethnos !== 'null') {
    query['details.ethnos'] = { $in: params.ethnos.split('|') };
  }
  
  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 ProfileEvents = new EventEmitter();  
      var id = req.params.id;
      var data = req.body;
    
      if (!id || !data) {
        res.status(500).json({ message: 'No profile id or data specified.', err: err });
        return;
      }

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

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

      Profiles.update(ProfileEvents, id, data);
    }
  });
}

function updateMessage (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 ProfileEvents = new EventEmitter();  
      var profileId = req.params.profileId;
      var messageId = req.params.messageId;
      var data = req.body;
    
      if (!profileId || !data) {
        res.status(500).json({ message: 'No profile id or data specified.', err: err });
        return;
      }

      ProfileEvents.once('updateMessage', (err, result) => {
        if (err) {
          res.status(500).json({message: 'Could not update profile id: ' + profileId + ' [' + err + ']', err: err});
        }

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

      Profiles.updateMessage(ProfileEvents, profileId, messageId, data);
    }
  });
}

Router.route('/approve/:id')
  .get((req, res) => {
    var ProfileEvents = new EventEmitter();
    var id = req.params.id;

    ProfileEvents.once('approveSubmission', (err, result) => {
      if (err) {
        res.status(500).json({ message: 'Could not approve user profile submission', err: err, profile: profile });
      }

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

    Profiles.approveSubmission(ProfileEvents, id);
  });

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 ProfileEvents = 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 }
          }
        };		
  
        ProfileEvents.once('find', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'There was an error getting the getting the profiles [' + err + ']', err: err });
          }
  
          if (result) {
            res.status(200).json(result);
          }		
        });

        Profiles.find(ProfileEvents, 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 ProfileEvents = 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 }
          }
        };		
  
        ProfileEvents.once('find', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'There was an error getting the profile list [' + err + ']', err: err });
          }
  
          if (result) {
            res.status(200).json(result);
          }		
        });

        Profiles.find(ProfileEvents, query);
      }
    });
  });

Router.route('/submission')
  .post((req, res) => {
    var ProfileEvents = new EventEmitter();
    var profile = req.body;

    ProfileEvents.once('processSubmission', (err, result) => {
      if (err) {
        res.status(500).json({ message: 'Could not process user profile submission', err: err, profile: profile });
      }

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

    Profiles.processSubmission(ProfileEvents, profile);
  });

Router.route('/submitted')
	.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 ProfileEvents = new EventEmitter();

        ProfileEvents.once('allSubmitted', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'Could not get profiles', err: err });
          }
      
          if (result) {
            res.status(200).json(result);
          }		
        });

        Profiles.allSubmitted(ProfileEvents);
      }
    });
	});
  
Router.route('/verified')
	.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 ProfileEvents = new EventEmitter();

        ProfileEvents.once('allVerified', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'Could not get profiles', err: err });
          }
      
          if (result) {
            res.status(200).json(result);
          }		
        });

        Profiles.allVerified(ProfileEvents);
      }
    });
	});

Router.route('/:profileId/messages/images/:which?')
  .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 method;
        var ProfileEvents = new EventEmitter();
        var profileId = req.params.profileId;

        switch (req.params.which) {
          case "all":
            method = 'allChatImages';
            break;
          case "sent":
            method = 'allChatImagesSent';
            break;
          case "recd":
          default:
            method = 'allChatImagesReceived';
        }

        ProfileEvents.once(method, (err, result) => {
          if (err) {
            res.status(500).json({ message: 'Could not get chat images for profile ' + profileId + '. [' + err + ']', err: err });
          }

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

        Profiles[method](ProfileEvents, profileId);
      }
    });
  });
  
Router.route('/:profileId/messages/:messageId?')
  .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 ProfileEvents = new EventEmitter();
        var profileId = req.params.profileId || null;
        var messageId = req.params.messageId || null;

        ProfileEvents.once('deleteMessage', (err, result) => {
          if (err) {
            res.status(500).json({ message: 'Could not delete message id: ' + messageId + ' [' + err + ']', err: err });
          }

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

        Profiles.deleteMessage(ProfileEvents, profileId, messageId);
      }
    });
  })
  .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 ProfileEvents = new EventEmitter();
        var profileId = req.params.profileId || null;
        var messageId = req.params.messageId || null;
        var method = messageId ? 'getMessage' : 'allMessages';

        ProfileEvents.once(method, (err, result) => {
          if (err) {
            res.status(500).json({ message: 'Could not get message' + (messageId ? ' ' : 's ') + 'for profile' + (profileId ? '' : 's') + ' [' + err + ']', err: err });
          }

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

        Profiles[method](ProfileEvents, profileId, messageId);
      }
    });
  })
  .patch( updateMessage )
  .put( updateMessage );

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 ProfileEvents = new EventEmitter();  
        var id = req.params.id;

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

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

        Profiles.delete(ProfileEvents, 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 ProfileEvents = new EventEmitter();
        var id = req.params.id || null;
        var method = id ? 'get' : 'all';

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

        Profiles[method](ProfileEvents, 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 ProfileEvents = new EventEmitter();
        var profile = Array.isArray(req.body) ? req.body : [ req.body ];
        var multi = profile.length > 1;

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

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

        Profiles.create(ProfileEvents, profile);
//       }
//     });
  })
	.put( update );

module.exports = Router;
