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

'use strict';

const path = require('path');

const express = require('express');
const captcha = require('svg-captcha');

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

class WelcomeController extends SiteController {

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

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

    captcha.loadFont(path.join(this.dtp.config.root, 'client', 'fonts', 'Dirty Sweb.ttf'));

    function preventUserAccess (req, res, next) {
      if (req.user) {
        return res.redirect(301, '/');
      }
      return next();
    }

    const router = express.Router();
    this.dtp.app.use('/welcome', welcomeLimiter, async (req, res, next) => {
      res.locals.currentView = 'welcome';
      return next();
    }, router);

    router.get('/core-member', preventUserAccess, this.getWelcomeCoreMember.bind(this));
    router.get('/signup/captcha', this.getSignupCaptcha.bind(this));
    router.get('/signup', preventUserAccess, this.getSignupView.bind(this));
    router.get('/login', preventUserAccess, this.getLoginView.bind(this));
    router.get('/', preventUserAccess, this.getHomeView.bind(this));

    return router;
  }

  async getWelcomeCoreMember (req, res) {
    res.render('welcome/core-member');
  }

  async getSignupCaptcha (req, res) {
    if (!req.session || !req.session.captcha || !req.session.captcha.signup) {
      return res.status(500).end('Session is not in a valid state for generating a captcha image');
    }
    const signupCaptcha = captcha(req.session.captcha.signup, {
      color: false,
      noise: 3,
      width: 300,
      height: 80,
    });
    res.set('Content-Type', 'image/svg+xml');
    res.set('Content-Length', signupCaptcha.length);
    res.status(200).send(signupCaptcha);
  }

  async getSignupView (req, res) {
    req.session.captcha = req.session.captcha || { };
    req.session.captcha.signup = captcha.randomText(4 + Math.floor(Math.random()*4));
    res.render('welcome/signup');
  }

  async getLoginView (req, res) {
    res.locals.loginResult = req.session.loginResult;
    res.render('welcome/login');
  }

  async getHomeView (req, res) {
    res.render('welcome/index');
  }
}

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