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

'use strict';

const express = require('express');

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

class NewsletterController extends SiteController {

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

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

    const upload = this.createMulter();

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

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

    router.param('newsletterId', this.populateNewsletterId.bind(this));

    router.post('/', upload.none(), this.postAddRecipient.bind(this));

    router.get('/:newsletterId',
      limiterService.createMiddleware(limiterService.config.newsletter.getView),
      this.getView.bind(this),
    );

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

  async populateNewsletterId (req, res, next, newsletterId) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      res.locals.newsletter = await newsletterService.getById(newsletterId);
      return next();
    } catch (error) {
      this.log.error('failed to populate newsletterId', { newsletterId, error });
      return next(error);
    }
  }

  async postAddRecipient (req, res) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      const displayList = this.createDisplayList('add-recipient');
      await newsletterService.addRecipient(req.body.email);
      displayList.showNotification(
        'You have been added to the newsletter. Please check your email and verify your email address.',
        'success',
        'bottom-center',
        10000,
      );
      res.status(200).json({ success: true, displayList });
    } catch (error) {
      this.log.error('failed to update account settings', { error });
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }

  async getView (req, res) {
    res.render('newsletter/view');
  }

  async getIndex (req, res, next) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.newsletters = await newsletterService.getNewsletters(res.locals.pagination);
      res.render('newsletter/index');
    } catch (error) {
      return next(error);
    }
  }
}

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