var Promise = require('bluebird')
var User = require('../database/user')
var logger = require('console-plus')
var PageUtils = require('./pageUtils.js')
var LayoutTable = require('./components/layoutTable')
var thisPage = '/users/:username'
var he = require('he')

module.exports = function (app, passport) {
  app.get(thisPage, app.isLoggedIn, function (req, res) {
    Promise.try(function () {
      return PageUtils.validateUsernameParameter(req, res)
    })
    .then(function () {
      Promise.try(function () {
        return User.findUserForView(req.params.username)
      }).then(function (user) {
        if (user === null) {
          res.redirect('/500')
          return
        }
        var layoutTable = new LayoutTable({columnsPerRow: 2})
        var displayedEmail = (app.isLoggedInAndAdminInline(req) ? user.email : 'Hidden')
        console.log('email: ' + user.email)
        layoutTable.addRow([{label: 'Username', value: user.username}])
        layoutTable.addRow([{label: 'E-mail', value: displayedEmail}])
        layoutTable.addRow([{label: 'Admin', value: user.admin ? 'Yes' : 'No'}])
        return Promise.all([user, layoutTable.getHTML()])
      }).spread(function (user, tableHtml) {
        var specificLinkData = []
        if (app.isLoggedInAndAdminInline(req)) {
          specificLinkData.push({
            'href': '/editUser/' + req.params.username,
            'label': 'Edit User'
          })
        }
        var headerString = he.decode(user.username)
        res.render('viewUserView.ejs', {
          infoMessages: req.flash('infoMessages'),
          errorMessages: req.flash('errorMessages'),
          user: req.user,
          pageValues: {
            header: headerString,
            table: tableHtml,
            specificLinks: specificLinkData
          }
        })
      })
      .catch(function (err) {
        if (err.stack) {
          logger.error(err.stack)
        } else {
          logger.error(err)
        }
        req.flash('errorMessages', 'Encountered an error while attempting to perform an action')
        res.redirect('/omg')
      })
    })
    .catch(Error, function (err) {
      logger.error(err.stack)
      res.redirect('/404')
    })
  })
}
