var express = require('express');
const db = require('../models');
var router = express.Router();
var lib = require('../lib');
var Message = db.Message;
var User = db.User;
var Op = db.Sequelize.Op;

async function getAllMessages(user) {
  if(user) {
    var follows = await user.getFollow();
    var timelineMessages = [];
    for(var i = 0; i < follows.length; i++) {
      timelineMessages[i] = follows[i]
      timelineMessages[i].messages = [];
      var messages = await follows[i].getMessages();
      for(var j = 0; j < messages.length; j++) {
        timelineMessages[i].messages.push(messages[j]);
      }
    }
    //var messages = fore
    return timelineMessages;
  }
}

/* POST a new message */
router.post('/add', async function(req, res, next) {
  var sessionId = req.cookies.sessionid;
  var user = await lib.getAuthUser(sessionId);
  if(user) {
    user.createMessage({ body: req.body.body });
    res.redirect('/');
  } else {
    res.redirect('/login');
  }
});

router.get('/timeline', async function(req, res, next) {
  var sessionId = req.cookies.sessionid;
  var user = await lib.getAuthUser(sessionId);
  var timeline = await getAllMessages(user);
  res.send(timeline);
});

router.get('/timeline2', async function(req, res, next) {
  var sessionId = req.cookies.sessionid;
  var user = await lib.getAuthUser(sessionId);
  if(user) {
    var follows = await user.getFollow();
    var userList = [];
    follows.forEach(element => {
      userList.push(element.id);
    });
    var userMessages = await db.User.findAll({
      include: Message,
      //required: true,
      where: {
        id: userList, 
        '$Messages.createdAt$': {
          [Op.like]: '2022%',
        }
      },
      
    });
    res.send(userMessages);
  } else {
    res.redirect('/login');
  }
});

module.exports = router;
