// Amira Abdel-Rahman
// (c) Massachusetts Institute of Technology 2020

/// Serve node.js to call python-urx library to interact with UR10s
/// https://github.com/SintefManufacturing/python-urx 

const { exec } = require("child_process");

var express = require('express');
var app = express();
const editJsonFile = require("edit-json-file");

var setup;

// will parse incoming JSON data and convert it into an object literal for you
app.use(express.json({limit: '50mb', extended: true}));
app.use(express.urlencoded({limit: '50mb', extended: true}));

//serve the html
app.use(express.static(__dirname + '/../')); // exposes index.html, per below

app.post("/", function(req, res) {
  // each key in req.body will match the keys in the data object that you passed in
  var myObject = req.body.data;
  setup=JSON.parse(myObject.setup);  
  
  console.log("run python_urx!");
  runPython_urx(setup);

  res.send("I am done");
});


port = 8080;
app.listen(port);
console.log(`Open http://localhost:${port}/demos/indexUR10.html in your browser`);

function runPython_urx(setup){
  // var dataToSend;
  // const python = exec('python', ['./assembly/python-urx/script1.py']);
  // const exec = spawn(‘python’, [‘script2.py’,’node.js’,’python’]);

  var root="../assembly/python-urx/";

  let outputFile = editJsonFile(`${__dirname}/`+root+`setup.json`);
  outputFile.set("setup", setup.ur10Setup);
  outputFile.save();
  console.log("saved the UR10 setup in ../assembly/python-urx/setup.json");
  console.log();

  if(setup.ur10Setup.parameters.run){
    console.log("Call python script:")
    var commands=[];
    commands.push("python " + root+setup.ur10Setup.parameters.pythonFileName +".py");
    runListCommand(commands,0);
    
  }else{
    console.log("didn't run the UR10");
  }

  if(setup.DEMSetup.parameters.run){
    var root="../simulation/dice_firmware/build/x86/src/sim/vis/";
    let outputFile = editJsonFile(`${__dirname}/`+root+`sim_config.json`);
    outputFile.set("setup", setup.DEMSetup);
    outputFile.save();
    console.log("saved the DEM setup in ../simulation/dice_firmware/build/x86/src/sim/vis/");
    console.log();
    console.log("Compile and run the DEM simulator:")
    var commands=[];
    if(setup.DEMSetup.parameters.make){
      //make first
      commands.push("cd " + "../simulation/dice_firmware/build/x86");
      commands.push("make");
      commands.push("cd " + "src/sim/vis/");

    }else{
      commands.push("cd " + root);
    }
    
    commands.push("./sim_vis_executable");
    runListCommand(commands,0);

  }else{
    console.log("didn't run DEM simulation");
  }
}

function runListCommand(commands,index){
  if (index<commands.length){
    console.log(commands[index]);
    exec(commands[index], (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout:`);
        console.log(`${stdout}`);
        runListCommand(commands,index+1);
    });
  }
}