// page.js
// Copyright (C) 2021 Digital Telepresence, LLC
// License: Apache-2.0

'use strict';

const express = require('express');

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

class PageController extends SiteController {

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

  async start ( ) {
    const { dtp } = this;
    const { limiter: limiterService } = dtp.services;

    const router = express.Router();
    dtp.app.use('/page', router);

    router.use(async (req, res, next) => {
      res.locals.currentView = 'page';
      return next();
    });

    router.param('pageSlug', this.populatePageSlug.bind(this));

    router.get('/:pageSlug',
      limiterService.createMiddleware(limiterService.config.page.getView),
      this.getView.bind(this),
    );
  }

  async populatePageSlug (req, res, next, pageSlug) {
    const { page: pageService } = this.dtp.services;
    try {
      res.locals.page = await pageService.getBySlug(pageSlug);
      if (!res.locals.page) {
        throw new SiteError(404, 'Page not found');
      }
      return next();
    } catch (error) {
      this.log.error('failed to populate pageSlug', { pageSlug, error });
      return next(error);
    }
  }

  async getView (req, res, next) {
    const { resource: resourceService } = this.dtp.services;
    try {
      await resourceService.recordView(req, 'Page', res.locals.page._id);
      res.locals.pageSlug = res.locals.page.slug;
      res.locals.pageTitle = `${res.locals.page.title} on ${this.dtp.config.site.name}`;
      res.render('page/view');
    } catch (error) {
      this.log.error('failed to service page view', { pageId: res.locals.page._id, error });
      return next(error);
    }
  }
}

module.exports = {
  slug: 'page',
  name: 'page',
  create: async (dtp) => {
    let controller = new PageController(dtp);
    return controller;
  },
};