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

/* GET users listing. */
router.get('/:username', async function(req, res, next) {
  var test = 123;
  var sessionId = req.cookies.sessionid;
  var search = req.params.username;
  var auth = await lib.getAuthUser(sessionId);
  if(auth) {
    var user = await User.findOne({
      where: {
        name: search,
      }
    });
    if(user) {
      var messages = await user.getMessages();
      var messageCount = await user.countMessages();
      res.render('user', {auth:auth, user:user, messages:messages, messageCount:messageCount});
    } else {
      res.redirect('/');
    }
  } else {
    res.redirect('/login');
  }
  
});

module.exports = router;
