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

'use strict';

const path = require('path');
const multer = require('multer');

const { SiteCommon } = require(path.join(__dirname, 'site-common'));
const { SiteError } = require(path.join(__dirname, 'site-error'));

class SiteController extends SiteCommon {

  constructor (dtp, component) {
    super(dtp, component);
  }

  async loadChild (filename) {
    let component = require(filename);
    let child = await component.create(this.dtp);
    return await child.start();
  }

  getPaginationParameters (req, maxPerPage) {
    const pagination = {
      p: parseInt(req.query.p || '1', 10),
      cpp: parseInt(req.query.cpp || maxPerPage.toString(), 10),
    };
    if (pagination.p < 1) {
      pagination.p = 1;
    }
    if (pagination.cpp > maxPerPage) {
      pagination.cpp = maxPerPage;
    }
    pagination.skip = (pagination.p - 1) * pagination.cpp;
    return pagination;
  }

  createMulter (slug, options) {
    if (!!slug && (typeof slug === 'object')) {
      options = slug;
      slug = this.component.slug;
    } else {
      slug = slug || this.component.slug;
    }
    options = Object.assign({
      dest: `/tmp/${this.dtp.config.site.domainKey}/${slug}/${this.component.slug}`
    }, options || { });

    return multer(options);
  }

  createDisplayList (name) {
    const { displayEngine: displayEngineService } = this.dtp.services;
    return displayEngineService.createDisplayList(name);
  }

  async createCsrfToken (req, name) {
    const { csrfToken } = this.dtp.platform.services;
    return csrfToken.create(req, { name });
  }

  async badRoute (res, req, next) {
    return next(new SiteError(400, "Page does not exist."));
  }
}

module.exports.SiteController = SiteController;
