const express = require('express');
const router = express.Router();
const db = require('qmi-cloud-common/mongo');
const passport = require('../passport');

/**
 * @swagger
 * /divvy/updates:
 *    post:
 *      description: DivvyCloud updates webhook
 *      tags:
 *        - admin
 *      requestBody:
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *      produces:
 *        - application/json
 *      responses:
 *        200:
 *          description: Notifications
 */
router.post('/updates', passport.ensureAuthenticatedAndAdmin, async (req, res, next) => {
  
  const dateNow = new Date();
  const now = dateNow.toISOString();
    try {
      
      const event = req.body; 
      let logEvent = event.logEvent || 'DivvyCloud';
      

      if ( event.cloudName === 'QMI Automation' ) {
             
        console.log(`${logEvent} (${now})# event received for subscription (${event.cloudName}) - provision (${event.provID}) -> new status (${event.instanceState})`);
        
        if ( event.provID && event.provID !== 'None' ) {

          let provision = await db.provision.getById(event.provID);
          
          if ( provision ) { 

            let id = provision._id.toString();

            console.log(`${logEvent} (${now})# provision (${id}) - scenario is (${provision.scenario} - v${provision.scenarioVersion})`);

            if ( provision.status === 'provisioned' || provision.status === 'error' ) {

              if ( event.instanceState === 'Stopped' ) {

                if ( provision.statusVms === 'Stopped' ) {
                  console.log(`${logEvent} (${now})# provision (${id}) - VMs were already Stopped!`);    
                } else {
                  
                  let timeRunning = db.utils.getNewTimeRunning(provision);
                  let patch = {
                    "statusVms": "Stopped", 
                    "timeRunning": timeRunning, 
                    "stoppedFrom": dateNow, 
                    "pendingNextAction": undefined
                  };
                  
                  let msg = "";

                  if ( provision.schedule && !provision.schedule.is24x7 ) {
                    patch["endDateOnSchedule"] = dateNow;

                    //This is temporary, only to make sure there is value
                    if ( !provision["startDateOnSchedule"] ) {
                      patch["startDateOnSchedule"] = dateNow;
                      msg = "startDateOS: " + dateNow.toISOString();
                    } else {
                      msg = "startDateOS: " + new Date(provision.startDateOnSchedule).toISOString();
                    }
                    msg += (" - endDateOS: " + dateNow.toISOString());
                  }
                  msg += ` - New totalTimeRunning: ${timeRunning} mins`;

                  await db.provision.update(id, patch);
                  console.log(`${logEvent} (${now})# provision (${id}) - VMs changed to Stopped!`);
                  db.event.add({ user: provision.user._id, provision: provision._id, type: 'vms.stop-schedule', message: msg });       
                }

              } else  if ( event.instanceState === 'Running' ) {

                if ( provision.statusVms === 'Running' ) {
                  console.log(`${logEvent} (${now})# provision (${id}) - VMs were already Running!`);  
                } else {
                  let patch = {
                    "statusVms": "Running", 
                    "runningFrom": dateNow, 
                    "pendingNextAction": undefined
                  };

                  // This is temporary, only to make sure there are values soon
                  if ( provision.schedule && !provision.schedule.is24x7 ) {
                    if ( !provision["startDateOnSchedule"] ) {
                      patch["startDateOnSchedule"] = dateNow;
                      patch["endDateOnSchedule"] = dateNow;
                    }
                  }

                  await db.provision.update(id, patch);
                  console.log(`${logEvent} (${now})# provision (${id}) - VMs changed to Running!`);
                  
                  db.event.add({ user: provision.user._id, provision: provision._id, type: 'vms.start-schedule', message: `TimeRunning so far: ${provision.timeRunning} mins` });
                }
              }
              
            } else {
              console.log(`${logEvent} (${now})# provision (${event.provID}) - Scenario not yet 'provisioned'`);
            }
            
          } else {
            console.log(`${logEvent} (${now})# provision (${event.provID}) - Provision not found.`);
          }

        } else {
          console.log(`${logEvent} (${now})# 'provID' attribute is missing.`);
        }

      } else {
        //console.log(`${logEvent} (${now}): event received for subscription (${event.cloudName}) --> won't be processed`);
      }

      return res.json(req.body);

    } catch (error) {
      console.log(`${logEvent} (${now})# error!!!!`, error);
      next(error);
    }
  });  

module.exports = router;