const tf = require('./docker/tf');
const db = require('qmi-cloud-common/mongo');
const path = require('path');
const sendEmail = require("qmi-cloud-common/send-email");
const barracuda = require("qmi-cloud-common/barracuda");

module.exports = async function(job){
    
    var destroyMongo = await db.destroy.update(job.data.id, {
        "status": "destroying", 
        "jobId": job.id,
        "logFile": path.join('/logs', 'destroy', `${job.data.id}.log`)
    });

    if ( !destroyMongo ) {
        console.log(`ProcessorDestroy# Not found Destroy object in Database (it should exist!), detroyId is: ${job.data.id}` );
        return Promise.reject({"success": false, "err": "Not found Destroy object in Worker"});
    }

    var provMongo = await db.provision.getById(job.data.provId);
    
    // Deleting Barracuda App if existed
    if ( provMongo.barracudaAppId ) {
        console.log(`ProcessorDestroy# Deleting Barracuda App...` );
        barracuda.deleteApp(provMongo);
    } else {
        console.log(`ProcessorDestroy# There is no barracuda to be deleted` );
    }

    db.event.add({ user: provMongo.user._id, provision: provMongo._id, type: 'provision.destroy-init' });

    return tf.destroy(destroyMongo, provMongo, job.data._scenario)
    .then(async function(res) {
        let update, update2;
        if ( res.output.indexOf("Error:") !== -1 ) {
            update = await db.destroy.update(destroyMongo._id,{"status": "error"});
            update2 = await db.provision.update(provMongo._id, {"isDestroyed": false});
        } else {
            update = await db.destroy.update(destroyMongo._id, {"status": "destroyed"});
            let timeRunning = db.utils.getNewTimeRunning(provMongo);
            update2 = await db.provision.update(provMongo._id, {"isDestroyed": true, "timeRunning": timeRunning, "pendingNextAction": undefined, "actualDestroyDate": new Date()});
            sendEmail.sendDestroyedSuccess(update2, job.data._scenario);
        }
        return { destroy: update, provision: update2 };
    }).then(async function(res) { 
        console.log(`ProcessorDestroy# Provision destroyed!` );
        db.event.add({ user: provMongo.user._id, provision: provMongo._id, type: 'provision.destroy-finished' });
        return Promise.resolve({"success": true, job: res});
    }).catch(function(err) {
        console.log("ProcessorDestroy# err", err);
        db.event.add({ user: provMongo.user._id, provision: provMongo._id, type: 'provision.destroy-error' });
        db.destroy.update(destroyMongo._id, {"status": "error", "isDestroyed": false});
        return Promise.reject({"success": false, "err": err});
    });
    
}


