// newsroom.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 NewsroomController 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('/newsroom', router);

    router.use(async (req, res, next) => {
      res.locals.currentView = module.exports.slug;
      return next();
    });

    router.param('feedId', this.populateFeedId.bind(this));

    router.get('/:feedId',
      limiterService.createMiddleware(limiterService.config.newsroom.getFeedView),
      this.getFeedView.bind(this),
    );

    router.get('/',
      limiterService.createMiddleware(limiterService.config.newsletter.getIndex),
      this.getHome.bind(this),
    );
  }

  async populateFeedId (req, res, next, feedId) {
    const { feed: feedService } = this.dtp.services;
    try {
      res.locals.feed = await feedService.getById(feedId);
      if (!res.locals.feed) {
        throw new SiteError(404, 'Feed not found');
      }
      return next();
    } catch (error) {
      this.log.error('failed to populate feedId', { feedId, error });
      return next(error);
    }
  }

  async getFeedView (req, res, next) {
    const { feed: feedService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 10);
      res.locals.newsroom = await feedService.getFeedEntries(res.locals.feed, res.locals.pagination);
      res.render('newsroom/feed-view');
    } catch (error) {
      this.log.error('failed to present newsroom home', { error });
      return next(error);
    }
  }

  async getHome (req, res, next) {
    const { feed: feedService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 12);
      res.locals.newsroom = await feedService.getFeeds(res.locals.pagination, { withEntries: true });
      res.render('newsroom/index');
    } catch (error) {
      this.log.error('failed to present newsroom home', { error });
      return next(error);
    }
  }
}

module.exports = {
  slug: 'newsroom',
  name: 'newsroom',
  create: (dtp) => { return new NewsroomController(dtp); },
};