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

'use strict';

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

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

class HiveController extends SiteController {

  constructor (dtp) {
    super(dtp, module.exports);
    this.services = [ ];
  }

  async start ( ) {
    const router = express.Router();
    this.dtp.app.use('/hive', router);

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

        /*
         * TODO: H1V3 authentication before processing request (HTTP Bearer token)
         */

        return next();
      },
    );

    router.use('/kaleidoscope', await this.loadChild(path.join(__dirname, 'hive', 'kaleidoscope')));
    this.services.push({ name: 'kaleidoscope', url: '/hive/kaleidoscope' });

    router.use('/user', await this.loadChild(path.join(__dirname, 'hive', 'user')));
    this.services.push({ name: 'user', url: '/hive/user' });

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

    return router;
  }

  async getHiveRoot (req, res) {
    res.locals.hiveView = 'home';
    res.status(200).json({
      pkg: { name: this.dtp.pkg.name, version: this.dtp.pkg.version },
      component: { name: this.component.name, slug: this.component.slug },
      host: this.dtp.pkg.name,
      description: this.dtp.pkg.description,
      version: this.dtp.pkg.version,
      services: this.services,
    });
  }
}

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