const MsRest = require('ms-rest-azure');
const computeManagementClient = require('azure-arm-compute');
const db = require("./mongo");
const sendEmail = require("./send-email");

const SUBSCRIPTION_ID = "62ebff8f-c40b-41be-9239-252d6c0c8ad9";

async function _getClient(scenarioName) {
    var scenario = await db.scenario.getOne({"name": scenarioName});
    var id = scenario.subscription? scenario.subscription.subsId : SUBSCRIPTION_ID;
    var credentials = await MsRest.loginWithMSI({ port: 50342 });
    console.log("Azure CLI authenticated", credentials);
    return  new computeManagementClient(credentials, id);
}

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

async function deallocate(provision, isSendEmailAfter ) {
    let rgName = provision.scenario.toUpperCase();
    rgName = rgName.replace(/AZQMI/g, 'QMI');
    rgName = rgName + "-" + provision._id.toString();

    console.log("Deallocating VMs for resource group: "+rgName);
    var computeClient = await _getClient(provision.scenario);
    let finalResult = await computeClient.virtualMachines.list(rgName);
    if ( finalResult && finalResult.length > 0 ) { 
        db.provision.update(provision._id, {"statusVms": "Stopping"});
    }
    await asyncForEach(finalResult, async function(vm)  {
        await computeClient.virtualMachines.deallocate(rgName, vm.name);
    });

    let timeRunning = db.utils.getNewTimeRunning(provision);
    await db.provision.update(provision._id.toString(), {"statusVms": "Stopped", "timeRunning": timeRunning, "stoppedFrom": new Date(), "pendingNextAction": undefined});
    
    if ( isSendEmailAfter && provision._scenario) {
        await sendEmail.sendVMsStopped(provision, provision._scenario);
    }
    
    console.log("All VMs DEALLOCATED for resource group: "+rgName);
}

async function start(provision){

    let rgName = provision.scenario.toUpperCase();
    rgName = rgName.replace(/AZQMI/g, 'QMI');
    rgName = rgName + "-" + provision._id.toString();

    console.log("Starting VMs for resource group: "+rgName);
    var computeClient = await _getClient(provision.scenario);
    let finalResult = await computeClient.virtualMachines.list(rgName);

    if ( finalResult && finalResult.length > 0 ) {
        db.provision.update(provision._id, {"statusVms": "Starting"});
    }
    await asyncForEach(finalResult, async function(vm)  {
        await computeClient.virtualMachines.start(rgName, vm.name);
    });
    let countExtend = db.utils.getNewCountExtend(provision);
    await db.provision.update(provision._id.toString(), {"statusVms": "Running", "runningFrom": new Date(), "countExtend": countExtend, "pendingNextAction": undefined});
    console.log("All VMs RUNNING for resource group: "+rgName);
}

async function getResourceGroupVms(rgName){
    return await computeClient.virtualMachines.list(rgName);
}

async function getAllVms(){ 
    return await computeClient.virtualMachines.listAll(rgName);
}

module.exports.start = start;
module.exports.deallocate = deallocate;
module.exports.getResourceGroupVms = getResourceGroupVms;
module.exports.getAllVms = getAllVms;