// admin/newsletter.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 NewsletterController extends SiteController {

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

  async start ( ) {
    const { jobQueue: jobQueueService } = this.dtp.services;
    const { config } = this.dtp;

    this.newsletterQueue = await jobQueueService.getJobQueue(
      'newsletter',
      config.jobQueues.newsletter,
    );

    const router = express.Router();
    router.use(async (req, res, next) => {
      res.locals.currentView = 'admin';
      res.locals.adminView = 'newsletter';
      return next();
    });

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

    router.post('/:newsletterId/transmit', this.postTransmitNewsletter.bind(this));
    router.post('/:newsletterId', this.postUpdateNewsletter.bind(this));
    router.post('/', this.postCreateNewsletter.bind(this));

    router.get('/compose', this.getComposer.bind(this));
    router.get('/job-status', this.getJobStatusView.bind(this));

    router.get('/:newsletterId', this.getComposer.bind(this));

    router.get('/', this.getIndex.bind(this));

    router.delete('/:newsletterId', this.deleteNewsletter.bind(this));

    return router;
  }

  async populateNewsletterId (req, res, next, newsletterId) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      res.locals.newsletter = await newsletterService.getById(newsletterId);
      if (!res.locals.newsletter) {
        throw new SiteError(404, 'Newsletter not found');
      }
      return next();
    } catch (error) {
      this.log.error('failed to populate newsletterId', { newsletterId, error });
      return next(error);
    }
  }

  async postTransmitNewsletter (req, res, next) {
    try {
      const displayList = this.createDisplayList('transmit-newsletter');
      res.locals.jobData = {
        newsletterId: res.locals.newsletter._id,
      };
      this.log.info('creating newsletter transmit job', { jobData: res.locals.jobData });
      res.locals.job = await this.newsletterQueue.add('transmit', res.locals.jobData);
      displayList.navigateTo(`/admin/job-queue/newsletter/${res.locals.job.id}`);
      res.status(200).json({ success: true, displayList });
    } catch (error) {
      this.log.error('failed to create newsletter transmit job', { error });
      return next(error);
    }
  }

  async postUpdateNewsletter (req, res, next) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      await newsletterService.update(res.locals.newsletter, req.body);
      res.redirect('/admin/newsletter');
    } catch (error) {
      this.log.error('failed to update newsletter', { newletterId: res.locals.newsletter._id, error });
      return next(error);
    }
  }

  async postCreateNewsletter (req, res, next) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      await newsletterService.create(req.user, req.body);
      res.redirect('/admin/newsletter');
    } catch (error) {
      this.log.error('failed to create newsletter', { error });
      return next(error);
    }
  }

  async getComposer (req, res) {
    res.render('admin/newsletter/editor');
  }

  async getJobStatusView (req, res, next) {
    const { jobQueue: jobQueueService } = this.dtp.services;
    try {
      res.locals.newsletterView = 'job-status';
      res.locals.queueName = 'newsletter';
      res.locals.newsletterQueue = await jobQueueService.getJobQueue(res.locals.queueName);
  
      res.locals.newsletterQueue = this.newsletterQueue;
      res.locals.jobCounts = await this.newsletterQueue.getJobCounts();
      res.locals.jobs = {
        waiting: await this.newsletterQueue.getWaiting(0, 5),
        active: await this.newsletterQueue.getActive(0, 5),
        delayed: await this.newsletterQueue.getDelayed(0, 5),
        failed: await this.newsletterQueue.getFailed(0, 5),
      };
      res.render('admin/newsletter/job-status');
    } catch (error) {
      this.log.error('failed to render job status view', { error });
      return next(error);
    }
  }

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

  async deleteNewsletter (req, res) {
    const { newsletter: newsletterService } = this.dtp.services;
    try {
      const displayList = this.createDisplayList('delete-newsletter');

      await newsletterService.deleteNewsletter(res.locals.newsletter);

      displayList.removeElement(`li[data-newsletter-id="${res.locals.newsletter._id}"]`);
      displayList.showNotification(
        `Newsletter "${res.locals.newsletter.title}" deleted`,
        'success',
        'bottom-center',
        3000,
      );
      res.status(200).json({ success: true, displayList });
    } catch (error) {
      this.log.error('failed to delete newsletter', {
        newsletterId: res.local.newsletter._id,
        error,
      });
      res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }
}

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