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

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(`Error: 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);

    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.sendDestroyed(update2, job.data._scenario);
        }
        return { destroy: update, provision: update2 };
    }).then(async function(res) {
        
        return Promise.resolve({"success": true, job: res});
    }).catch(function(err) {
        console.log("Processor Destroy: err", err);
        db.destroy.update(destroyMongo._id, {"status": "error", "isDestroyed": false});
        return Promise.reject({"success": false, "err": err});
    });
    
}


