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

'use strict';

const path = require('path');
const glob = require('glob');

const express = require('express');

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

class FormController extends SiteController {

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

  async start ( ) {
    const {
      chat: chatService,
      limiter: limiterService,
      session: sessionService,
    } = this.dtp.services;

    try {
      this.forms = glob.sync(path.join(this.dtp.config.root, 'app', 'views', 'form', '*pug')) || [ ];
      this.forms = this.forms.map((filename) => path.parse(filename));
    } catch (error) {
      this.log.error('failed to detect requestable forms', { error });
      this.forms = [ ];
      // fall through
    }

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

    router.use(
      sessionService.authCheckMiddleware({ requireLogin: true }),
      chatService.middleware({ maxOwnedRooms: 25, maxJoinedRooms: 50 }),
      async (req, res, next) => {
        res.locals.currentView = module.exports.slug;
        return next();
      },
    );

    router.get(
      '/:formSlug',
      limiterService.createMiddleware(limiterService.config.form.getForm),
      this.getForm.bind(this),
    );
  }

  async getForm (req, res, next) {
    const { formSlug } = req.params;
    const form = this.forms.find((form) => form.name === formSlug);
    if (!form) {
      return next(new SiteError(400, 'Invalid form'));
    }
    res.render(`form/${form.name}`);
  }
}

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