// samples/controller.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 HomeController extends SiteController {

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

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

    const upload = this.createMulter();

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

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

    router.param('itemId', this.populateItemId.bind(this));

    router.post(
      '/item',
      limiterService.createMiddleware(limiterService.config.home.postItemCreate),
      upload.none(),
      this.postItemCreate.bind(this),
    );

    router.get(
      '/item/:itemId',
      limiterService.createMiddleware(limiterService.config.sample.getItemView),
      this.getItemView.bind(this),
    );

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

  async populateItemId (req, res, next, itemId) {
    const { item: itemService } = this.dtp.services;
    try {
      res.locals.item = await itemService.getById(itemId);
      if (!res.locals.item) {
        throw new SiteError(404, 'Item not found');
      }
      return next();
    } catch (error) {
      return next(error);
    }
  }

  async postItemCreate (req, res, next) {
    const { item: itemService } = this.dtp.services;
    try {
      const item = await itemService.create(req.user, req.body);
      res.redirect(`/item/${item._id}`);
    } catch (error) {
      this.log.error('failed to create item', { error });
      return next(error);
    }
  }

  async getItemView (req, res) {
    res.render('item/view');
  }

  async getHome (req, res, next) {
    const { announcement: announcementService } = this.dtp.services;
    try {
      res.locals.announcements = await announcementService.getLatest(req.user);
      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); },
};