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('/profile/: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');
  }
  
});

router.get('/settings', async function(req, res, next) {
  var sessionId = req.cookies.sessionid;
  var auth = await lib.getAuthUser(sessionId);
  if(auth) {
    res.render('settings', { auth:auth });
  } else {
    res.redirect('/login');
  }
  
});

router.post('/settings', async function(req, res, next) {
  var sessionId = req.cookies.sessionid;
  var auth = await lib.getAuthUser(sessionId);
  var newData = {};
  if(req.body.bio != '') {
    newData.bio = req.body.bio;
  }
  if(req.body.name != '') {
    newData.name = req.body.name;
  }
  if(req.files) {
    if(req.files.avatar.data) {
      newData.avatar = req.files.avatar.data;
    }
  }
  if(auth) {
    console.log(req);
    console.log(req.files);
    await auth.update(newData);
    res.redirect('/user/settings');
  } else {
    res.redirect('/login');
  }
});

router.get('/avatar/:id', async function(req, res, next) {
  var user = await db.User.findOne({
    where: {
      id: req.params.id
    }
  });
  res.contentType('image/png');
  if(user.avatar) {
    res.end(Buffer.from(user.avatar.buffer, 'base64'));
  } else {
    res.send();
  }
  //res.send(user.avatar.buffer);
});

module.exports = router;
