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

'use strict';

const express = require('express');

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

class ManifestController 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('/manifest.json', router);

    router.use(async (req, res, next) => {
      res.locals.currentView = this.component.slug;
      return next();
    });

    router.get('/',
      limiterService.createMiddleware(limiterService.config.manifest.getManifest),
      this.getManifest.bind(this),
    );
  }

  async getManifest (req, res, next) {
    const DEFAULT_THEME_COLOR = '#4a4a4a';
    const DEFAULT_BACKGROUND_COLOR = '#1a1a1a';
    try {
      const manifest = {
        theme_color: DEFAULT_THEME_COLOR,
        background_color: DEFAULT_BACKGROUND_COLOR,
        display: 'fullscreen',
        scope: '/',
        start_url: '/',
        name: this.dtp.config.site.name,
        short_name: this.dtp.config.site.name,
        description: this.dtp.config.site.description,
        icons: [ ],
      };
  
      [512, 384, 256, 192, 144, 96, 72, 48, 32, 16].forEach((size) => {
        manifest.icons.push({
          src: `/img/icon/${this.dtp.config.site.domainKey}/icon-${size}x${size}.png`,
          sizes: `${size}x${size}`,
          type: 'image/png'
        });
      });
  
      res.status(200).json(manifest);
    } catch (error) {
      return next(error);
    }
  }
}

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