// dtp-sites.js
// Copryright (C) 2022 DTP Technologies, LLC
// Licence: Apache-2.0

'use strict';

const DTP_COMPONENT = { name: 'Sites', slug: 'sites' };

require('dotenv').config();

const path = require('path');

const { SitePlatform, SiteLog } = require(path.join(__dirname, 'lib', 'site-lib'));

module.rootPath = __dirname;
module.pkg = require(path.join(module.rootPath, 'package.json'));
module.config = {
  environment: process.env.NODE_ENV,
  component: DTP_COMPONENT,
  root: module.rootPath,
  site: require(path.join(module.rootPath, 'config', 'site')),
  http: require(path.join(module.rootPath, 'config', 'http')),
  https: require(path.join(module.rootPath, 'config', 'https')),
  registerMiddleware: async (dtp, app) => {
    module.log.info('registering Page service middleware');
    const {
      feed: feedService,
      gabTV: gabTvService,
      page: pageService,
      siteLink: siteLinkService,
      venue: venueService,
    } = module.services;
    app.use(
      feedService.middleware({ maxEntryCount: 5 }),
      pageService.menuMiddleware.bind(pageService),
      siteLinkService.middleware(),
      venueService.channelMiddleware(),
      gabTvService.channelMiddleware()
    );
  },
};

module.log = new SiteLog(module, module.config.component);

module.shutdown = async ( ) => {
  await SitePlatform.shutdown();
};

(async ( ) => {

  process.on('unhandledRejection', (error, p) => {
    module.log.error('Unhandled rejection', {
      error: error,
      promise: p,
      stack: error.stack
    });
  });
  
  process.on('warning', (error) => {
    module.log.alert('warning', { error });
  });
  
  process.once('SIGINT', async ( ) => {
    module.log.info('SIGINT received');
    module.log.info('requesting shutdown...');
    await module.shutdown();
    const exitCode = await SitePlatform.shutdown();
    process.nextTick(( ) => {
      process.exit(exitCode);
    });
  });
  
  process.once('SIGUSR2', async ( ) => {
    await SitePlatform.shutdown();
    process.kill(process.pid, 'SIGUSR2');
  });

  try {
    await SitePlatform.startPlatform(module);
    await SitePlatform.startWebServer(module);
  } catch (error) {
    module.log.error(`failed to start DTP ${module.config.component.name}`, { error });
    process.exit(-1);
  }

})();