// admin/user.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const express = require('express');

const { SiteController } = require('../../../lib/site-lib');

class UserController extends SiteController {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  async start ( ) {
    const router = express.Router();
    router.use(async (req, res, next) => {
      res.locals.currentView = 'admin';
      res.locals.adminView = 'user';
      return next();
    });

    router.param('userId', this.populateUserId.bind(this));

    router.post('/:userId', this.postUpdateUser.bind(this));

    router.get('/:userId', this.getUserView.bind(this));
    router.get('/', this.getHomeView.bind(this));

    return router;
  }

  async populateUserId (req, res, next, userId) {
    const { user: userService } = this.dtp.services;
    try {
      res.locals.userAccount = await userService.getUserAccount(userId);
      return next();
    } catch (error) {
      return next(error);
    }
  }

  async postUpdateUser (req, res, next) {
    const { user: userService } = this.dtp.services;
    try {
      await userService.updateForAdmin(res.locals.userAccount, req.body);
      res.redirect('/admin/user');
    } catch (error) {
      return next(error);
    }
  }

  async getUserView (req, res, next) {
    const { comment: commentService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.recentComments = await commentService.getForAuthor(res.locals.userAccount, res.locals.pagination);
      res.render('admin/user/form');
    } catch (error) {
      this.log.error('failed to produce user view', { error });
      return next(error);
    }
  }

  async getHomeView (req, res, next) {
    const { user: userService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 10);
      res.locals.userAccounts = await userService.getUserAccounts(res.locals.pagination, req.query.u);
      res.locals.totalUserCount = await userService.getTotalCount();
      res.render('admin/user/index');
    } catch (error) {
      return next(error);
    }
  }
}

module.exports = {
  name: 'adminUser',
  slug: 'admin-user',
  create: async (dtp) => { return new UserController(dtp); },
};