// 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 limiterConfig = limiterService.config.newsroom;

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

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

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

    router.get('/feed',
      limiterService.createMiddleware(limiterConfig.getUnifiedFeed),
      this.getUnifiedFeed.bind(this),
    );

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

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

  async populateFeedId (req, res, next, feedId) {
    const {
      feed: feedService,
      logan: loganService,
    } = 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) {
      loganService.sendRequestEvent(module.exports, req, {
        level: 'error',
        event: 'populateFeedId',
        message: error.message,
        data: { feedId, error },
      });
      return next(error);
    }
  }

  async getUnifiedFeed (req, res) {
    const {
      feed: feedService,
      logan: loganService,
    } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.newsroom = await feedService.getNewsfeed(res.locals.pagination);

      loganService.sendRequestEvent(module.exports, req, {
        level: 'info',
        event: 'getUnifiedFeed',
        data: { fmt: req.query.fmt || 'html' },
      });

      switch (req.query.fmt) {
        case 'json':
          res.status(200).json(res.locals.newsroom);
          break;

        default:
          res.render('newsroom/unified-feed');
          break;
      }
    } catch (error) {
      loganService.sendRequestEvent(module.exports, req, {
        level: 'error',
        event: 'getUnifiedFeed',
        message: error.message,
        data: { error },
      });
      res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }

  async getFeedView (req, res, next) {
    const {
      feed: feedService,
      logan: loganService,
    } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 10);
      res.locals.newsroom = await feedService.getFeedEntries(res.locals.feed, res.locals.pagination);

      loganService.sendRequestEvent(module.exports, req, {
        level: 'info',
        event: 'getFeedView',
        data: {
          feed: {
            _id: res.locals.feed._id,
            title: res.locals.feed.title,
          },
        },
      });

      res.render('newsroom/feed-view');
    } catch (error) {
      loganService.sendRequestEvent(module.exports, req, {
        level: 'error',
        event: 'getFeedView',
        message: error.message,
        data: { error },
      });
      return next(error);
    }
  }

  async getHome (req, res, next) {
    const {
      feed: feedService,
      logan: loganService,
    } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 12);
      res.locals.newsroom = await feedService.getFeeds(res.locals.pagination, { withEntries: true });

      loganService.sendRequestEvent(module.exports, req, {
        level: 'info',
        event: 'getHome',
      });

      res.render('newsroom/index');
    } catch (error) {
      loganService.sendRequestEvent(module.exports, req, {
        level: 'error',
        event: 'getHome',
        message: error.message,
        data: { error },
      });
      return next(error);
    }
  }
}

module.exports = {
  logId: 'ctl:newsroom',
  index: 'newsroom',
  className: 'NewsroomController',
  create: (dtp) => { return new NewsroomController(dtp); },
};