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

'use strict';

const express = require('express');

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

class AnnouncementController extends SiteController {

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

  async start ( ) {
    const { comment: commentService } = this.dtp.services;

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

    const upload = this.createMulter();

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

    router.param('announcementId', this.populateAnnouncementId.bind(this));

    router.post('/:announcementId/comment', upload.none(), commentService.commentCreateHandler('Announcement', 'announcement'));

    router.get('/:announcementId', this.getAnnouncementView.bind(this));
    router.get('/', this.getHome.bind(this));

    return router;
  }

  async populateAnnouncementId (req, res, next, announcementId) {
    const { announcement: announcementService } = this.dtp.services;
    try {
      res.locals.announcement = await announcementService.getById(announcementId);
      if (!res.locals.announcement) {
        this.log.error('announcement not found', { announcementId });
        return next(new SiteError(404, 'Announcement not found'));
      }
      return next();
    } catch (error) {
      return next(error);
    }
  }

  async getAnnouncementView (req, res, next) {
    const { comment: commentService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 10);
      res.locals.comments = await commentService.getForResource(res.locals.announcement, ['published'], res.locals.pagination);
      res.render('announcement/view');
    } catch (error) {
      this.log.error('failed to render announcement view', { error });
      return next(error);
    }
  }

  async getHome (req, res, next) {
    const { announcement: announcementService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 10);
      res.locals.announcements = await announcementService.getAnnouncements(res.locals.pagination);
      res.render('announcement/index');
    } catch (error) {
      return next(error);
    }
  }
}

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