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

'use strict';

const express = require('express');

const mongoose = require('mongoose');
const NetHost = mongoose.model('NetHost');
const NetHostStats = mongoose.model('NetHostStats');

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

class HostController 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 = 'host';
      return next();
    });

    router.param('hostId', this.populateHostId.bind(this));

    router.post('/:hostId/deactivate', this.postDeactiveHost.bind(this));

    router.get('/:hostId', this.getHostView.bind(this));

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

    return router;
  }

  async populateHostId (req, res, next, hostId) {
    try {
      res.locals.host = await NetHost.findOne({ _id: hostId });
      return next();
    } catch (error) {
      return next(error);
    }
  }

  async postDeactiveHost (req, res) {
    try {
      const displayList = this.createDisplayList('deactivate-host');

      await NetHost.updateOne(
        { _id: res.locals.host._id },
        {
          $set: { status: 'inactive' },
        },
      );

      displayList.removeElement(`tr[data-host-id="${res.locals.host._id}"]`);
      displayList.showNotification(
        `Host "${res.locals.host.hostname}" deactivated`,
        'success',
        'bottom-center',
        3000,
      );
      res.status(200).json({ success: true, displayList });

    } catch (error) {
      this.log.error('failed to deactivate host', {
        hostId: res.local.host._id,
        error,
      });
      res.status(error.statusCode || 500).json({
        success: false,
        message: error.message,
      });
    }
  }

  async getHostView (req, res, next) {
    try {
      res.locals.stats = await NetHostStats
        .find({ host: res.locals.host._id })
        .sort({ created: -1 })
        .limit(30)
        .lean();
      res.locals.stats = res.locals.stats.reverse();
      res.render('admin/host/view');
    } catch (error) {
      return next(error);
    }
  }

  async getHomeView (req, res, next) {
    try {
      const HOST_SELECT = '_id created updated hostname status platform arch totalmem freemem';

      res.locals.activeHosts = await NetHost
        .find({ status: 'active' })
        .select(HOST_SELECT)
        .sort({ updated: 1 })
        .lean();

      res.locals.crashedHosts = await NetHost
        .find({ status: 'crashed' })
        .select(HOST_SELECT)
        .sort({ updated: 1 })
        .lean();

      res.render('admin/host/index');
    } catch (error) {
      return next(error);
    }
  }
}

module.exports = {
  name: 'adminHost',
  slug: 'admin-host',
  create: async (dtp) => { return new HostController(dtp); },
};