// Import dependencies
const passport = require('passport');
const express = require('express');
const config = require('../config/main');
const jwt = require('jsonwebtoken');

// Set up middleware
const requireAuth = passport.authenticate('jwt', { session: false });

// Load models
const User = require('./models/user');
const Chat = require('./models/chat');

// Export the routes for our app to use
module.exports = function(app) {
  // API Route Section

  // Initialize passport for use
  app.use(passport.initialize());

  // Bring in defined Passport Strategy
  require('../config/passport')(passport);

  // Create API group routes
  const apiRoutes = express.Router();

  // Register new users
  apiRoutes.post('/register', function(req, res) {
    
    if(!req.body.fname || !req.body.lname || !req.body.email || !req.body.password) {
      res.status(400).json({ success: false, message: 'Please enter email and password.' });
    } else {
      const newUser = new User({
        fname: req.body.fname,
        lname: req.body.lname,
        email: req.body.email,
        password: req.body.password
      });

      // Attempt to save the user
      newUser.save(function(err) {
        if (err) {
          return res.status(400).json({ success: false, message: 'That email address already exists.'});
        }
        res.status(201).json({ success: true, message: 'Successfully created new user.' });
      });
    }
  });

  // Authenticate the user and get a JSON Web Token to include in the header of future requests.
  apiRoutes.post('/authenticate', function(req, res) {
    User.findOne({
      email: req.body.email
    }, function(err, user) {
      if (err) throw err;

      if (!user) {
        res.status(401).json({ success: false, message: 'Authentication failed. User not found.' });
      } else {
        // Check if password matches
        user.comparePassword(req.body.password, function(err, isMatch) {
          if (isMatch && !err) {
            // Create token if the password matched and no error was thrown
            const token = jwt.sign(user, config.secret/*, {
              expiresIn: 10080 // in seconds
            }*/);
            res.status(200).json({ success: true, token: 'JWT ' + token, user: user });
          } else {
            res.status(401).json({ success: false, message: 'Authentication failed. Passwords did not match.' });
          }
        });
      }
    });
  });

  // Search user using email address
  apiRoutes.get('/user/:email',requireAuth,function(req, res) {
    User.findOne({
      email: req.params.email
    }, function(err, user) {
      if (err) throw err;

      if (!user) {
        res.status(200).json({ success: false, message: 'User not found.', user: null });
      } else {
        res.status(200).json({ success: true, message: 'User found.', user : user });
      }
    });
  });



  // Protect chat routes with JWT
  // GET messages for authenticated user
  apiRoutes.get('/chat', requireAuth, function(req, res) {
    Chat.find({$or : [{'to': req.user._id}, {'from': req.user._id}]}, function(err, messages) {
      if (err)
        res.status(400).send(err);

      res.status(400).json(messages);
    });
  });

  // POST to create a new message from the authenticated user
  apiRoutes.post('/chat', requireAuth, function(req, res) {
    const chat = new Chat();
        chat.from = req.user._id;
        chat.to = req.body.to;
        chat.message_body = req.body.message_body;

        // Save the chat message if there are no errors
        chat.save(function(err) {
            if (err)
                res.status(400).send(err);

            res.status(201).json({ message: 'Message sent!' });
        });
  });

  // PUT to update a message the authenticated user sent
  apiRoutes.put('/chat/:message_id', requireAuth, function(req, res) {
    Chat.findOne({$and : [{'_id': req.params.message_id}, {'from': req.user._id}]}, function(err, message) {
      if (err)
        res.send(err);

      message.message_body = req.body.message_body;

      // Save the updates to the message
      message.save(function(err) {
        if (err)
          res.send(err);

        res.json({ message: 'Message edited!' });
      });
    });
  });

  // DELETE a message
  apiRoutes.delete('/chat/:message_id', requireAuth, function(req, res) {
    Chat.findOneAndRemove({$and : [{'_id': req.params.message_id}, {'from': req.user._id}]}, function(err) {
      if (err)
        res.send(err);

      res.json({ message: 'Message removed!' });
    });
  });

  // Set url for API group routes
  app.use('/api', apiRoutes);
};

@@ -2966,32 +2966,41 @@
 outes.get('/chat
+/:user_id
 ', requireAuth, 
@@ -3040,16 +3040,25 @@
 d(%7B$or :
+ %5B%7B$and :
  %5B%7B'to':
@@ -3058,29 +3058,35 @@
 %5B%7B'to': req.
+params.
 user
-.
 _id%7D, %7B'from
@@ -3096,32 +3096,124 @@
 req.user._id%7D%5D%7D,
+%7B$and : %5B%7B'to': req.user._id%7D, %7B'from': req.params.user_id%7D%5D%7D%5D%7D,null,%7Bsort:%7BcreatedAt : 1%7D%7D,
  function(err, m
@@ -3283,33 +3283,33 @@
      res.status(
-4
+2
 00).json(message
@@ -3301,24 +3301,27 @@
 0).json(
+ %7B 
 messages
 );%0A    %7D
@@ -3312,16 +3312,29 @@
 messages
+ : messages %7D
 );%0A    %7D

add chat option