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

'use strict';

const express = require('express');
// const multer = require('multer');

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

class CoreUserController 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 = 'core-user';
      return next();
    });

    router.param('coreUserId', this.populateCoreUserId.bind(this));

    router.post('/:coreUserId', this.postUpdateCoreUser.bind(this));

    router.get('/:coreUserId', this.getCoreUserView.bind(this));
    router.get('/', this.getIndex.bind(this));

    return router;
  }

  async populateCoreUserId (req, res, next, coreUserId) {
    const { coreNode: coreNodeService } = this.dtp.services;
    try {
      res.locals.userAccount = await coreNodeService.getUserByLocalId(coreUserId);
      if (!res.locals.userAccount) {
        throw new SiteError(404, 'Core Member not found');
      }
      return next();
    } catch (error) {
      this.log.error('failed to populate coreUserId', { coreUserId, error });
      return next(error);
    }
  }

  async postUpdateCoreUser (req, res, next) {
    const { coreNode: coreNodeService } = this.dtp.services;
    try {
      await coreNodeService.updateUserForAdmin(res.locals.userAccount, req.body);
      res.redirect('/admin/core-user');
    } catch (error) {
      return next(error);
    }
  }

  async getCoreUserView (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/core-user/form');
    } catch (error) {
      this.log.error('failed to produce user view', { error });
      return next(error);
    }
  }

  async getIndex (req, res, next) {
    const { coreNode: coreNodeService } = this.dtp.services;
    const search = { };
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.users = await coreNodeService.searchUsers(search, res.locals.pagination);
      res.render('admin/core-user/index');
    } catch (error) {
      this.log.error('failed to render Core User home', {
        search,
        pagination: res.locals.pagination,
        error,
      });
      return next(error);
    }
  }
}

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