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

/* GET home page. */
router.get('/me', async function(req, res, next) {
  console.log(req.cookies.sessionid);
  var sessionId = req.cookies.sessionid;
  var user = await lib.getAuthUser(sessionId);
  if(user) {
    var messages = await user.getMessages({
      order: [
        ['id', 'DESC'],
      ],
      limit: 10
    });
    var messageCount = await user.countMessages();
    res.render('me', { auth:user, messages:messages, messageCount:messageCount });
  } else {
    res.redirect('/login');
  }
  
});

router.get('/', async function(req, res, next) {
  var sessionId = req.cookies.sessionid;
  var user = await lib.getAuthUser(sessionId);
  if(user) {
    var follows = await user.getFollow({
      attributes: {
        include: [
          'id',
        ]
      }
    });
    var userList = [];
    userList.push(user.id);
    follows.forEach(element => {
      userList.push(element.id);
    });
    var userMessages = await db.Message.findAll({
      include: User,
      where: {
        '$User.id$': {
          [Op.in]: userList
        }
      },
      order: [
        ['updatedAt', 'DESC']
      ]
    });
    //console.log(await userMessages[0].getUsers());
    res.render('index', {auth:user, messages:userMessages, messageCount:3});
  } else {
    res.redirect('/login');
  }
});

module.exports = router;
