
var myArgs = process.argv.slice(2);

if ( myArgs.length < 3 ) {
    console.log("Missing args", myArgs);
    process.exit(0);
}

const IS_REAL = myArgs[2] !== 'test';
const RUNNING_PERIOD = myArgs[1]; //Days
const RUNNING_LIMIT_HOURS_WARNING = 24*(RUNNING_PERIOD-1);
const RUNNING_LIMIT_HOURS_STOP = 24*RUNNING_PERIOD;

const db = require('qmi-cloud-common/mongo');
const sendEmail = require("qmi-cloud-common/send-email");
const moment = require('moment');
const azurecli = require('qmi-cloud-common/azurecli');

function timeRunning(p) {
    let runningFromTime = p.runningFrom? new Date(p.runningFrom).getTime() : new Date(p.created).getTime();
    let totalRunningFromTime;
    if (p.statusVms !== 'Stopped' && p.statusVms !== 'Starting' && !p.isDestroyed) {
        totalRunningFromTime = Math.abs(new Date().getTime() - runningFromTime);
    }
    let duration = moment.duration(totalRunningFromTime);
    p.duration = {
        hours: Math.floor(duration.asHours()),
        complete: Math.floor(duration.asDays()) +"d "+duration.hours()+"h "+duration.minutes()
    };
}

async function asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
}

async function init(type) {
    var limit, cb;
    var filter = {
        "isDestroyed":false, 
        "isDeleted": false, 
        "statusVms": "Running"
    };
    if ( type === "warning" ) {
        limit = RUNNING_LIMIT_HOURS_WARNING;  
        filter.pendingNextAction = {$ne: "stopVms"};
        cb = doSendEmailWarning;
    } else if ( type === "exec" ) {
        limit = RUNNING_LIMIT_HOURS_STOP;
        filter.pendingNextAction = "stopVms";
        cb = doStop;
    } else {
        console.log("Invalid 'type'. Do nothing.");
        return;
    }

    let provisions = await db.provision.get(filter);
    let scenarios = await db.scenario.get();

    await asyncForEach(provisions.results, async function(p)  {
        var _scenario = scenarios.results.filter(s=>{
            return s.name === p.scenario
        });
        if ( _scenario.length ){
            p._scenario = _scenario[0];
        }
        timeRunning(p);
        if (!IS_REAL) {
            console.log(`${p._id} - limit: ${limit} hs - actual duration: ${p.duration.hours} hs`);
        }
        if ( p.duration && p.duration.hours >= limit) {
            await cb(p);
        }
    });
}

const doSendEmailWarning = async function(p) {
    if ( p.pendingNextAction === 'stopVms') {
        console.log(`Warning email Stop already sent. Wait for pending action to complete.`);
    } else {
        let msg = `Send warning STOP email - ${p.user.displayName} (${p.user.upn}) about provision '${p._scenario.title}' (${p._id}) being 'Running' more than ${RUNNING_LIMIT_HOURS_WARNING} hours (exactly ${p.duration.complete})`;
        console.log(msg);
        if ( IS_REAL ) {
            await db.provision.update(p._id, {"pendingNextAction": "stopVms"});
            await sendEmail.sendWillStopIn24(p, p._scenario);
            await db.notification.add({ provision: p._id.toString(), type: 'warningStop', message: msg });    
        }       
    }  
};

const doStop = async function(p) {
    try {
        let msg = `VMs stopped - ${p.user.displayName} (${p.user.upn}) about provision '${p._scenario.title}' (${p._id}) being 'Running' more than ${RUNNING_LIMIT_HOURS_STOP} hours (exactly ${p.duration.complete})`
        console.log(msg);

        if ( IS_REAL ) {     
            await azurecli.deallocate(p, true);
            await db.notification.add({ provision: p._id.toString(), type: 'stop', message: msg });
        }  
         
    } catch (error) {
        console.log("doStop Error", error);
        await db.provision.update(p._id, {"statusVms": "Error_Stopping"});
    }    
};

function check(type) {
    init(type).then(function(){
        db.mongoose.connection.close()
        process.exit(0);
        
    }).catch(function(e){
        db.mongoose.connection.close()
        console.log("Error", e);
        process.exit(0);
    });
}


// --------------------------------
switch (myArgs[0]) {
    case 'warning':
        check("warning");
        break;
    case 'exec':
        check("exec");
        break;
    default:
        console.log('Sorry, that is not something I know how to do.');
        process.exit(0);
}



