var express = require('express'),
    router = express.Router(),

    fs = require('fs'),//Para manejar archivos
    exec = require('child_process').exec,//para ejecutar comandos
    shortid = require('shortid'),//para que no se repitan archivos
    multer = require('multer'),//Recibe datos
    bodyParser = require('body-parser'),//para sacar los datos de los formularios

    //para enviar correos electrónicos
    nodemailer = require('nodemailer'),
    transporter = nodemailer.createTransport('smtps://user%40gmail.com:pass@smtp.gmail.com'),

    path = require('path');

router.use(multer({
  dest: './public/images/user-images/'
}).single('file'));


var deleteData = function(path) {
    console.log("Deleting data!: ", path);
    var ok = true;
    var child = exec('rm -rf ' + path);
    child.stdout.on('data', function(data) {
        console.log('stdout: ' + data);
    });
    child.stderr.on('data', function(data) {
        console.log('stderr: ' + data);
        ok = false;
    });
    child.on('close',function(code, signal){
      if (ok)
        console.log("Data was succesfully deleted.");
      else
        console.log("Data could not be removed");
    });
    return ok;
};

module.exports = function(app, mountPoint){

  /*-----------Routing-------------------*/
  router.get('/', function(req, res, next) {
    res.render('index.ejs', { answere1: '', answere2: '', answere3: '' });
  });

  router.get('/error', function(req, res, next) {
    res.render('error.ejs', { message_err : '' });
  });

  router.get('/grafica', function(req, res, next) {
    var aux = req.flash('ans');
    res.render('index.ejs', { answere1: aux[0], answere2: aux[1] });
  });

  router.post('/send-email', function(req, res, next) {
    var name = req.body.uname;
    var email = req.body.cmail;
    var from_ = '"' + name + '" <' + email + '>';
    var message = req.body.ccoment;

    var transporter = nodemailer.createTransport({
          service: 'Gmail' ,
          auth: {
              user: '', // Your email id
              pass: '' // Your password
          }
    });

    var mailOptions = {
      from: from_, // sender address
      to: '', // list of receivers
      subject: 'Mensaje desde Brain-Densitometry', // Subject line
      html:  "<p><strong>From : " + email + "</strong></p><p>" + message + "</p>",
    };
    //console.log("from1 : " + mailOptions.from);
    //return;

    transporter.sendMail(mailOptions, function(error, info){
      if (error) {
          console.log(error);
          res.render('error.ejs', { message_err : 'NO SE PUDO ENVIAR EL MENSAJE' });
      } else {
          console.log('Mensaje enviado: ' + info.response);
          //res.render('index.ejs');
          res.redirect('/#Contacto');
      };
    });

  });

  router.post("/upload",function(req, res, next){
    console.log("------------------------1------------------------");
    var original_name = req.file.originalname;
    console.log("original name:"+original_name);
    var path = req.file.path;
    console.log("path:"+path);
    var file_name = req.file.filename;//ruta completa con el nombre del archivo
    console.log("file name:"+file_name);
    var destination = req.file.destination;//donde queda guardado el archivo
    var id = shortid.generate();//req.cookies.id || shortid.generate();
    console.log(req.file);//aquí queda toda la información de la imágen
    var ok = true; // variable que controla la ejecución de los child-processes

    if (req.file.mimetype !== "application/zip"){
      res.render('error.ejs', { message_err : 'Debe ingresar una carpeta comprimida en zip' });
      return;
    }

    res.cookie('id',id);//para independizacion de archivos
    console.log("cookie id from /upload: ", req.cookies.id);
    console.log("id /upload : ",req.cookies.id);

      var html = 'Archivo: '+original_name+' subido con exito.';
      /*file_name_aux nos ayuda a enviar bien el nombre para la ejecucion
      del archivo desde cualquier terminal*/

      var file_name_aux;

      //descomprime
      var command1 = "cd "+ destination,
          command2 = "mkdir " + file_name + id,
          command3 = "unzip -d " + file_name + id +" "+file_name;

      var child = exec(command1 + ";" + command2 + ";" + command3);
      console.log("comando child1 : ", command1 + ";" + command2 + ";" + command3);
      console.log("-----------------------------2-----------------------");
      child.stdout.on('data', function(data) {
        console.log('stdout: ' + data);
        console.log(destination + file_name + id)
        var files = fs.readdirSync(destination + file_name + id);

          console.log("mypath : ", destination + file_name + id);
          console.log("files : ", files);
          if (files.length >= 1)
            file_name_aux = files[0].replace(/ /g, "\\ ");

          //else ok = false;
      });
      child.stderr.on('data', function(data) {
        res.render('error.ejs', { message_err : data });
        console.log('stderr: ' + data);
        ok = false;
      });
      child.on('close', function(code, signal){
        console.log("nombre nuevo: ",file_name_aux);
        console.log("1");
        console.log("ok : ", ok);
        if (ok && file_name_aux) { // child se ejecutó con éxito
          //ejecuta
          console.log("1.1");
          command1 = "cd ../../source",
          command2 = "python3 nipypeTest.py ../web/app/" + path + id + "/" + file_name_aux + " " + id;
          console.log("command2 = ", command2);
          var child2 = exec(command1 + ";" + command2);
          console.log("-----------------------------3-----------------------");
          child2.stdout.on('data', function(data) {
              console.log('stdout: ' + data);
          });
          child2.stderr.on('data', function(data) {
              res.render('error.ejs', { message_err : data });
              console.log('stdout: ' + data);
              ok = false;
          });
          child2.on('close',function(code, signal){
            console.log("2");
            if (ok) {
              console.log("2.1");
              var file_path = '../../data/density'+id+'.txt';
              //file_path = '../../data/density.txt';
              if (fs.existsSync(file_path)) {
                  var contents = fs.readFileSync(file_path).toString();
                  console.log("CONTENTS: ",contents);
                  var html2 = 'La densidad cerebral es: '+ contents ;
              }
              else ok = false;

              if (ok && deleteData(path+' '+path+id)){
                console.log("3.1");
                console.log("success3!");
                req.flash('ans',[html,html2]);
                res.redirect('/grafica');
              } // cierra ok de child3
              else res.render('error.ejs', { message_err : "" });
            } // cierra ok de child2
            else res.render('error.ejs', { message_err : "" });
          });
        } // cierra ok de child
        else{
          console.log("va a remover : ", destination + file_name + id + " " +destination + file_name + id);
          deleteData(destination + file_name + id + " " + destination + file_name);
          res.render('error.ejs', { message_err : "" });
        }
      });
  });


  /*-----------Sockets-------------------*/
  var io = app.io,
      path = "",
      data = "",
      cookieID = "",
      users = [],
      processes = []; // procesos que se estan realizando

  io.on('connection', function(socket){
    console.info('New client connected (id=' + socket.id + ').');

    socket.on('delete data', function (path){
      deleteData(path);
    });

    socket.emit('serverReady', 'El servidor está listo.');

    socket.on('clientReady', function (info) {
      console.log("socket.on clientReady");
      path = info.path;
      data = info.data;
      cookieID = info.cookieID;
      if (users.indexOf(cookieID) ==! -1){
          users.push(cookieID);
          console.log("inserted : " , cookieID);
          console.log("having : ", users);
      }
      console.log("COOKIEID : " , cookieID);

    });

    //Se eliminan archivos basura cuando abandona la página
    socket.on('disconnect', function() {
        console.info('Client gone: (id=' + socket.id + ').');
    });

  });

  app.use(mountPoint, router);

}
