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

'use strict';

const express = require('express');

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

class LogController 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 = 'log';
      return next();
    });

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

    return router;
  }

  async getIndex (req, res, next) {
    const { log: logService } = this.dtp.services;
    try {
      res.locals.query = req.query;

      res.locals.components = await logService.getComponentSlugs();
      res.locals.pagination = this.getPaginationParameters(req, 25);

      const search = { };
      if (req.query.component) {
        search.component = { slug: req.query.component };
      }
      res.locals.logs = await logService.getRecords(search, res.locals.pagination);

      res.locals.totalLogCount = await logService.getTotalCount();

      res.render('admin/log/index');
    } catch (error) {
      return next(error);
    }
  }
}

module.exports = {
  name: 'adminLog',
  slug: 'admin-log',
  create: async (dtp) => { return new LogController(dtp); },
};