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

'use strict';

const express = require('express');
// const multer = require('multer');

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

class TagController extends SiteController {

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

  async start ( ) {
    const { dtp } = this;
    // const {
    //   post: postService,
    //   limiter: limiterService,
    //   session: sessionService,
    // } = dtp.services;

    // const authRequired = sessionService.authCheckMiddleware({ requiredLogin: true });

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

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

    router.param('tagSlug', this.populateTagSlug.bind(this));

    router.get('/:tagSlug', this.getSearchView.bind(this));
  }

  async populateTagSlug (req, res, next, tagSlug) {
    const { post: postService } = this.dtp.services;
    try {
      var allPosts = false;
      var statusArray = ['published'];
      if (req.user) {
        if (req.user.flags.isAdmin) {
          statusArray.push('draft');
          allPosts = true;
        }
      }
      res.locals.allPosts = allPosts;
      res.locals.tagSlug = tagSlug;
      tagSlug = tagSlug.replace("_", " ");
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.posts = await postService.getByTags(tagSlug, res.locals.pagination, statusArray);
      res.locals.tag = tagSlug;
      return next();
    
    } catch (error) {
      this.log.error('failed to populate tagSlug', { tagSlug, error });
      return next(error);
    }
  }

  async getSearchView (req, res) {
    try {
      res.locals.pageTitle = `Tag ${res.locals.tag} on ${this.dtp.config.site.name}`;
      
      res.render('tag/view');
    } catch (error) {
      this.log.error('failed to service post view', { postId: res.locals.post._id, error });
      throw SiteError("Error getting tag view:", error );
    }
  }


  async getIndex (req, res, next) {
    const { post: postService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.posts = await postService.getPosts(res.locals.pagination);
      res.render('tag/index');
    } catch (error) {
      return next(error);
    }
  }
}

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