var express = require('express');
var fileUpload = require('express-fileupload');
var nodemailer = require('nodemailer');
var exec = require('ssh-exec');
var Client = require('ssh2').Client;

var connSettings = {
    host: 'paget.univ-littoral.fr',
    port: 22,
    username: 'etu',
    password: 'Password'
};

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'ptech011@gmail.com',
        pass: 'eilco700'
    }
});



var router = express.Router();

// Get Homepage
router.get('/',  function(req, res){
    res.render('index');
});

function ensureAuthenticated(req, res, next) {
    if(req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/users/login');
    }
}

router.get('/compute',  ensureAuthenticated, function(req, res){
    res.render('compute');
});

router.post('/test', function(req,res) {
    console.log(req.body);
    
    if (Object.keys(req.files).length == 0) {
        return res.status(400).send('No files were uploaded.');
    }

    var com = req.body.nIt + " " + req.body.meth + " " + (req.body.ginit ? "1": "0") + " ";
    com += (req.body.modph ? "1": "0") + " " + req.body.alpha + " " + req.body.beta; 
    console.log(com);
    //var com = req.body.nIt + req.body
    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    //var sampleFile = req.files.foo;
    //console.log(sampleFile.name);
    //res.redirect('/compute');
});

router.get('/test', function (res, res) {
    res.render('test');

    
    /*
    var conn = new Client();
                        conn.on('ready', function() {
                            conn.sftp(function(err, sftp) {
                                if (err) throw err;

                                var moveFrom = "/home/etu/Documents/DataTest/Data_syntetic_Ecume_all_Xb_200_234_Gi_New_Bounds.xlsx";
                                var moveTo = "C:\\Users\\Mehdi\\Documents\\P_Tech\\Login-Register\\uploaded\\Data_syntetic_Ecume_all_Xb_200_234_Gi_New_Bounds.xlsx";

                                sftp.fastGet(moveFrom, moveTo , {}, function(downloadError){
                                    if(downloadError) throw downloadError;
                                });
                            });
                        }).connect(connSettings);
                        */
});


router.post('/compute', function(req, res) {
    if (Object.keys(req.files).length == 0) {
        return res.status(400).send('No files were uploaded.');
    }

    var com = " " + req.body.nIt + " " + req.body.meth + " " + (req.body.ginit ? "1": "0") + " ";
    com += (req.body.modph ? "1": "0") + " " + req.body.alpha + " " + req.body.beta + " "; 
    console.log(com);

    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    var sampleFile = req.files.foo;
    sampleFile.name = sampleFile.name.replace(' ', '_');
    console.log(sampleFile.name);
    if(req.user)
    console.log(req.user);
    else console.log('no user');
    //console.log(req.user.email ? req.user.email : "no Email of user");
    //console.log(sampleFile);
    // Use the mv() method to place the file somewhere on your server

    sampleFile.mv('C:\\Users\\Mehdi\\Documents\\P_Tech\\Login-Register\\uploaded\\' + sampleFile.name, function(err) {
        if (err) return res.status(500).send(err);
        console.log("File moved");
        var conn = new Client();
        conn.on('ready', function() {
            conn.sftp(function(err, sftp) {
                if (err) throw err;

                var fs = require("fs"); // Use node filesystem
                var readStream = fs.createReadStream( "C:\\Users\\Mehdi\\Documents\\P_Tech\\Login-Register\\uploaded\\" + sampleFile.name );
                var writeStream = sftp.createWriteStream( "/home/etu/Documents/DataTest/" + sampleFile.name );

                writeStream.on('close',function () {
                    console.log( "File transferred succesfully" );
                    res.send('Un email vous sera envoyé contenats vos calculs, dès qu\'ils seront prêt.');
                    exec('/home/etu/software/NMFbin/NMFIHM /home/etu/Documents/DataTest/'+sampleFile.name + com +'/home/etu/Documents/DataTest/Res_'+sampleFile.name, {
                        user: 'etu',
                        host: 'paget.univ-littoral.fr',
                        password: 'Password'
                    }, function (err, stdout, stderr) {
                        if(err) throw err;
                        console.log(stdout);
                        console.log(stderr);
                        var conn = new Client();
                        conn.on('ready', function() {
                            conn.sftp(function(err, sftp) {
                                if (err) throw err;

                                var moveFrom = "/home/etu/Documents/DataTest/Res_"+sampleFile.name;
                                var moveTo = "C:\\Users\\Mehdi\\Documents\\P_Tech\\Login-Register\\uploaded\\Res_"+sampleFile.name;

                                sftp.fastGet(moveFrom, moveTo , {}, function(downloadError){
                                    if(downloadError) throw downloadError;
                                    console.log("Succesfully uploaded");
                                    var mailOptions = {
                                        from: 'ptech011@gmail.com',
                                        to: req.user.email ? req.user.email : 'touimi.benj@gmail.com',
                                        subject: 'Résultat calcul SPAMAP',
                                        text: 'Bonjour,\nVeuillez trouver ci-joint les fichiers obtenus après calucl.\nCordialement.',
                                        attachments: [{
                                            filename:'Res_'+sampleFile.name,
                                            path: "C:\\Users\\Mehdi\\Documents\\P_Tech\\Login-Register\\uploaded\\Res_"+sampleFile.name
                                        }]
                                    };

                                    transporter.sendMail(mailOptions, function(error, info){
                                        if (error) {
                                            console.log(error);
                                        } else {
                                            console.log('Email sent: ' + info.response);
                                        }
                                    });

                                });
                            });
                        }).connect(connSettings);
                    })

                });

                writeStream.on('end', function () {
                    console.log( "sftp connection closed" );
                    conn.close();
                });

                // initiate transfer of file
                readStream.pipe( writeStream );
            });
        }).connect(connSettings);

    });

});



module.exports = router;