'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Note = mongoose.model('Note'),
    Notifications = mongoose.model('Notification'),
    Comment = mongoose.model('Comment'),
    User = mongoose.model('User'),
    _ = require('lodash');


/**
 * List of notes
 */
exports.all = function(req, res) {
    var q = Comment.find({onNote : req.query.noteId});


    
    q.sort({ dateCreate : 'desc' }).populate('createBy', 'name username avatar').exec(function(err, comments) {
        if (err) {
            console.log(err);
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(comments);
        }
    });

};

// Get note by id
exports.comment = function(req, res, next, id) {
    Comment.load(id, function(err, comment) {
        if (err) return next(err);
        if (!comment) return next(new Error('Failed to load comment ' + id));
        req.comment = comment;
        next();
    });
};

/**
 * Create a ntoe
 */

 exports.create = function(req, res) {
    var comment = new Comment(req.body);
    comment.createBy = req.user;
    // todo: send to class and member
    comment.save(function(err) {
        if (err) {
            return res.send('users/signup', {
                errors: err.errors,
                comment: comment
            });
        } else {
            // update comment
            res.jsonp(comment);
            // find and pregmatch username from list
            var re = /(@\w+)/gi;
            var found = comment.content.match(re);
            var userArr =[];
            for (var i = 0; i < found.length; i++) {
                userArr[i] = found[i].replace('@','');
            };
            User.find({ username : {'$in': userArr} },'id name username',function(err,users){
                if (err) {
                    console.error(err)
                }
                else
                    for (var i = 0; i < users.length; i++) {
                        userid = users[i]._id;
                        var notify = new Notifications();
                        notify.source = comment;
                        notify.from = req.user;
                        notify.to = userid;
                        notify.type = 'comment';
                        notify.content =  req.user.name + ' has mentioned you on comment.' ;
                        notify.save();
                    };
            })

            Note.load(comment.onNote , function(err, note) {
                if (err) return next(err);
                if (!note) return next(new Error('Failed to load note ' + id));
                var query = Comment.find( {onNote : comment.onNote } );
                    query.count(function(err,totals){
                        if (err) {
                            console.error(err);
                        }
                        else
                        {
                            note.totalComments = totals;

                            // notify to member and owner of note
                            for (var i = 0; i < note.sendToMembers.length; i++) {
                                var userid = note.sendToMembers[i];
                                var notify = new Notifications();
                                notify.source = comment;
                                notify.from = req.user;
                                notify.to = userid;
                                notify.type = 'comment';
                                notify.content =  req.user.name + ' has commented on note "' + note.title + '"' ;
                                notify.save();
                            };

                            note.save(); 
                        }
                    });
            });
            
        }
    });
};

exports.show = function(req, res) {
    res.jsonp(req.comment);
};
@@ -1579,25 +1579,202 @@
     
-var userArr =%5B%5D;%0A
+console.log('find username in ' + comment.content);%0A            console.log(found);%0A            var userArr =%5B%5D;%0A            if(found != undefined && (found instanceof Array))%0A            %7B%0A    
     
@@ -1814,32 +1814,36 @@
 .length; i++) %7B%0A
+    
                 
@@ -1885,35 +1885,43 @@
 ');%0A            
+ 
-%7D;%0A
+   %7D;%0A    
             User
@@ -2006,32 +2006,36 @@
                 
+ 
+   
 if (err) %7B%0A     
@@ -2021,32 +2021,36 @@
      if (err) %7B%0A
+    
                 
@@ -2080,34 +2080,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -2131,32 +2131,36 @@
                 
+  
+  
 for (var i = 0; 
@@ -2204,24 +2204,28 @@
             
+    
 userid = use
@@ -2251,32 +2251,36 @@
                 
+   
+ 
 var notify = new
@@ -2313,32 +2313,36 @@
                 
+    
 notify.source = 
@@ -2342,32 +2342,36 @@
 urce = comment;%0A
+    
                 
@@ -2418,32 +2418,36 @@
                 
+    
 notify.to = user
@@ -2442,32 +2442,36 @@
 fy.to = userid;%0A
+    
                 
@@ -2495,32 +2495,36 @@
 pe = 'comment';%0A
+    
                 
@@ -2616,32 +2616,36 @@
                 
+    
 notify.save();%0A 
@@ -2655,32 +2655,36 @@
                 
+ 
+   
 %7D;%0A            %7D
@@ -2682,18 +2682,49 @@
         
-%7D)
+    %7D)%0A            %7D%0A            
 %0A%0A      

Debug - comment on note