// venue.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 VenueController extends SiteController {

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

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

    const router = express.Router();

    this.dtp.app.use('/venue', async (req, res, next) => {
      res.locals.currentView = 'venue';
      return next();
    }, router);

    router.param('channelSlug', this.populateChannelSlug.bind(this));

    router.get(
      '/:channelSlug',
      limiterService.createMiddleware(limiterService.config.venue.getVenueEmbed),
      this.getVenueEmbed.bind(this),
    );

    router.get(
      '/',
      this.getHome.bind(this),
    );

    return router;
  }

  async populateChannelSlug (req, res, next, channelSlug) {
    const { venue: venueService } = this.dtp.services;
    try {
      res.locals.channel = await venueService.getChannelBySlug(channelSlug, { withCredentials: true });
      if (!res.locals.channel) {
        throw new SiteError(404, `Channel "${channelSlug}" does not exists on ${this.dtp.config.site.name}. Please check the link/URL you used, and try again.`);
      }

      res.locals.channelCredentials = res.locals.channel.credentials;
      delete res.locals.channel.credentials;

      return next();
    } catch (error) {
      this.log.error('failed to populate Venue channel by slug', { channelSlug, error });
      return next(error);
    }
  }

  async getVenueEmbed (req, res) {
    res.render('venue/embed');
  }

  async getHome (req, res, next) {
    const { venue: venueService} = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 10);
      res.locals.channels = await venueService.getChannels(res.locals.pagination);
      res.render('venue/index');
    } catch (error) {
      this.log.error('failed to present the Venue home', { error });
      return next(error);
    }
  }
}

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