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

'use strict';

const path = require('path');

const express = require('express');

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

class HomeController extends SiteController {

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

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

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

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

    router.param('policyDocument', this.populatePolicyDocument.bind(this));

    router.get('/policy/:policyDocument', this.getPolicyDocument.bind(this));

    router.get('/',
      limiterService.createMiddleware(limiterService.config.home.getHome),
      this.getHome.bind(this),
    );
  }

  async populatePolicyDocument (req, res, next, policyDocument) {
    const { markdown: markdownService } = this.dtp.services;
    try {
      const basePath = path.join(this.dtp.config.root, 'app', 'views', 'policy');
      switch (policyDocument) {
        case 'terms-of-service':
          res.locals.policyDocument = await markdownService.renderFile(path.join(basePath, 'terms-of-service.md'));
          break;
        case 'privacy':
          res.locals.policyDocument = await markdownService.renderFile(path.join(basePath, 'privacy.md'));
          break;
        default:
          throw new SiteError(404, 'Document not found');
      }
      return next();
    } catch (error) {
      return next(error);
    }
  }

  async getPolicyDocument (req, res) {
    res.render('policy/view');
  }

  async getHome (req, res, next) {
    const { announcement: announcementService, hive: hiveService, post: postService } = this.dtp.services;
    try {
      res.locals.announcements = await announcementService.getLatest(req.user);
      res.locals.featuredPosts = await postService.getFeaturedPosts(3);
      res.locals.constellationTimeline = await hiveService.getConstellationTimeline(req.user, { skip: 0, cpp: 5 });

      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.posts = await postService.getPosts(res.locals.pagination);

      res.render('index');
    } catch (error) {
      this.log.error('failed to render home view', { error });
      return next(error);
    }
  }
}

module.exports = {
  slug: 'home',
  name: 'home',
  isHome: true,
  create: async (dtp) => { return new HomeController(dtp); },
};