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

'use strict';

const express = require('express');
// const multer = require('multer');

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

class CoreNodeController extends SiteController {

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

  async start ( ) {
    const router = express.Router();
    router.use(async (req, res, next) => {
      res.locals.currentView = 'admin';
      res.locals.adminView = 'core-node';
      return next();
    });

    router.param('coreNodeId', this.populateCoreNodeId.bind(this));

    router.post('/connect', this.postCoreNodeConnect.bind(this));

    router.get('/resolve', this.getCoreNodeResolveForm.bind(this));
    router.get('/connect', this.getCoreNodeConnectForm.bind(this));

    router.get('/:coreNodeId', this.getCoreNodeView.bind(this));
    router.get('/', this.getIndex.bind(this));

    return router;
  }

  async populateCoreNodeId (req, res, next, coreNodeId) {
    const { coreNode: coreNodeService } = this.dtp.services;
    try {
      res.locals.coreNode = await coreNodeService.getCoreById(coreNodeId);
      if (!res.locals.coreNode) {
        throw new SiteError(404, 'Core Node not found');
      }
      return next();
    } catch (error) {
      this.log.error('failed to populate Core Node', { coreNodeId, error });
      return next(error);
    }
  }

  async postCoreNodeConnect (req, res) {
    const { coreNode: coreNodeService } = this.dtp.services;

    try {
      const { core, networkPolicy } = await coreNodeService.resolveCore(req.body.host);
      res.locals.core = core;
      res.locals.networkPolicy = networkPolicy;
    } catch (error) {
      this.log.error('failed to resolve Core', { host: req.body.host, error });
      res.locals.error = error;
      res.locals.message = error.message;
      return res.render('admin/core-node/connect-result');
    }

    if (res.locals.networkPolicy === 'closed') {
      return res.render('admin/core-node/connect-result');
    }

    const CORE_SCHEME = process.env.DTP_CORE_AUTH_SCHEME || 'https';
    const siteConfig = Object.assign({ }, this.dtp.config.site);

    if (req.body.callbackUri) {
      siteConfig.coreAuth.callbackUrl = `${CORE_SCHEME}://${this.dtp.config.site.domain}${req.body.callbackUri}`;
    } else {
      const callbackUri = `/auth/core/${res.locals.core._id}/callback`;
      siteConfig.coreAuth.callbackUrl = `${CORE_SCHEME}://${this.dtp.config.site.domain}${callbackUri}`;
    }

    try {
      res.locals.txConnect = await coreNodeService.sendRequest(res.locals.core, {
        method: 'POST',
        url: '/core/connect/node',
        tokenized: true,
        body: {
          pkg: {
            name: this.dtp.pkg.name,
            version: this.dtp.pkg.version,
          },
          site: siteConfig,
        },
      });

      const { response } = res.locals.txConnect;
      if (response.success && (response.status === 'connected') && response.connect) {
        await coreNodeService.setCoreOAuth2Credentials(res.locals.core, response.connect);
      }

      res.render('admin/core-node/connect-result');
    } catch (error) {
      this.log.error('failed to create Core Node connection request', { error });
      res.locals.error = error;
      res.locals.message = error.message;
      res.render('admin/core-node/connect-result');
    }
  }

  async getCoreNodeResolveForm (req, res) {
    res.render('admin/core-node/resolve');
  }

  async getCoreNodeConnectForm (req, res) {
    res.render('admin/core-node/connect');
  }

  async getCoreNodeView (req, res, next) {
    const { coreNode: coreNodeService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.requestHistory = await coreNodeService.getCoreRequestHistory(res.locals.coreNode, res.locals.pagination);
      res.render('admin/core-node/view');
    } catch (error) {
      this.log.error('failed to render Core Node view', { error });
      return next(error);
    }
  }

  async getIndex (req, res, next) {
    const { coreNode: coreNodeService } = this.dtp.services;
    try {
      res.locals.pagination = this.getPaginationParameters(req, 20);
      res.locals.coreNodes = await coreNodeService.getConnectedCores(res.locals.pagination);
      res.render('admin/core-node/index');
    } catch (error) {
      this.log.error('failed to render Core Node home', { error });
      return next(error);
    }
  }
}

module.exports = {
  name: 'adminCoreNode',
  slug: 'admin-core-node',
  create: async (dtp) => { return new CoreNodeController(dtp); },
};