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

'use strict';

const express = require('express');

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

class SiteFeedController extends SiteController {

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

  async start ( ) {
    const router = express.Router();
    this.dtp.app.use('/feed', router);

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

    router.get('/rss', this.getRssFeed.bind(this));
    router.get('/atom', this.getAtomFeed.bind(this));
    router.get('/json', this.getJsonFeed.bind(this));
    
    router.get('/', this.getHome.bind(this));

    return router;
  }

  async getRssFeed (req, res) {
    const { feed: feedService } = this.dtp.services;
    try {
      const feed = await feedService.getSiteFeed();
      const rss = feed.rss2();
      res.set('Content-Type', 'application/rss+xml');
      res.set('Content-Length', rss.length);
      res.send(rss);
    } catch (error) {
      res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }

  async getAtomFeed (req, res) {
    const { feed: feedService } = this.dtp.services;
    try {
      const feed = await feedService.getSiteFeed();
      const atom = feed.atom1();
      res.set('Content-Type', 'application/rss+xml');
      res.set('Content-Length', atom.length);
      res.send(atom);
    } catch (error) {
      res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }

  async getJsonFeed (req, res) {
    const { feed: feedService } = this.dtp.services;
    try {
      const feed = await feedService.getSiteFeed();
      const json = feed.json1();
      res.set('Content-Type', 'application/json');
      res.set('Content-Length', json.length);
      res.send(json);
    } catch (error) {
      res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }

  async getHome (req, res) {
    res.render('feed/index');
  }
}

module.exports = {
  slug: 'feed',
  name: 'feed',
  create: async (dtp) => { return new SiteFeedController(dtp); },
};