'use strict';

const express = require('express');
const router = express.Router();
const fs = require('fs');
var global_error = "";

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

//post http://localhost:8080/latex2pdf
router.post('/', function (req, res) {
	let latex = req.body;
	var local_timestamp = new Date().valueOf();
	var EPSpositions = [];
	
	latex.content = latex.content.replace(/\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=1\\textwidth]{/g, "\\begin{figure}[h!]\n\\centering\n\\includegraphics[width=1\\textwidth]{" + local_timestamp);
	fs.writeFile("/tmp/test" + local_timestamp , latex.content, function(err){
		if(err){
			return console.log(err);
		}
	});
	if(latex.images_array != null){
		for(var h = 0; h < latex.images_array.length; ++h){
			var base64Data = latex.images_array[h].replace(/^data:image\/png;base64,/,"").replace(/^data:image\/jpeg;base64,/,"");
			if(/^data:image\/x-eps;base64,/.test(base64Data)){
				base64Data = base64Data.replace(/^data:image\/x-eps;base64,/, "");
				var binaryData = new Buffer(base64Data, 'base64').toString('ascii');
				require("fs").writeFile(local_timestamp + "image" + h + ".eps", binaryData, function(err) {
					console.log(err);
				});
				EPSpositions.push(1);
			}else{
				var binaryData = new Buffer(base64Data, 'base64').toString('binary');

				require("fs").writeFile(local_timestamp + "image" + h + ".png", binaryData, "binary", function(err) {
					console.log(err);
				});
				EPSpositions.push(0);
			}
		}
	}

	var ls = spawn("xelatex", ["-interaction=nonstopmode", "/tmp/test" + local_timestamp]);

	ls.stdout.on("data", data => {
		console.log(`${data}`)
        	var error =  `${data}`;
		if(error.search("No page of output") != -1 || error.search("! ") != -1) global_error = error;
	});

	ls.stderr.on("data", data => {
		console.log(`stderr: ${data}`);
	});

	ls.on('error', (error) => {
		console.log(`error: ${error.message}`);
	});

	ls.on("exit", code => {
		if(latex.content.includes("\\tableofcontents")){
			var tex2 = spawn("xelatex", ["-interaction=nonstopmode", "/tmp/test" + local_timestamp]);
			tex2.stdout.on("data", data => {
				console.log(`stdout: ${data}`);
			});

			tex2.stderr.on("data", data => {
				console.log(`stderr: ${data}`);
			});

			tex2.on('error', (error) => {
				console.log(`error: ${error.message}`);
			});
			tex2.on("close", code => {
				deleteImages(latex.images_array, local_timestamp, EPSpositions);
				if(code == 0){
					const contents = fs.readFileSync('test' + local_timestamp + '.pdf', {encoding: 'base64'});
					const rm = spawn("rm", ["test" + local_timestamp + ".out", "test" + local_timestamp + ".log", "test" + local_timestamp + ".pdf", "test" + local_timestamp + ".aux", "/tmp/test" + local_timestamp]);
					res.status(200).send({
						msg: "1",
						content: contents
					});
				}else{
					const rm = spawn("rm", ["test" + local_timestamp + ".out", "test" + local_timestamp + ".log", "test" + local_timestamp + ".pdf", "test" + local_timestamp + ".aux", "/tmp/test" + local_timestamp]);
					res.status(400).send({
						msg: "0",
						er: global_error
					});
				}
			});
		}else{
			deleteImages(latex.images_array, local_timestamp, EPSpositions);
			if(code == 0){
				const contents = fs.readFileSync('test' + local_timestamp + '.pdf', {encoding: 'base64'});
				const rm = spawn("rm", ["test" + local_timestamp + ".out", "test" + local_timestamp + ".log", "test" + local_timestamp + ".pdf", "test" + local_timestamp + ".aux", "/tmp/test" + local_timestamp]);
				res.status(200).send({
					msg: "1",
					content: contents
				});
			}else{
				const rm = spawn("rm", ["test" + local_timestamp + ".out", "test" + local_timestamp + ".log", "test" + local_timestamp + ".pdf", "test" + local_timestamp + ".aux", "/tmp/test" + local_timestamp]);
				res.status(400).send({
					msg: "0",
					er: global_error
				});
			}
		}
	});
	
});
function deleteImages(images_array, timestamp, EPS_array){
	if(images_array != null){
		for(var i = 0; i < images_array.length; ++i){
			if(EPS_array[i]){
				var rm = spawn("rm", [timestamp + "image" + i + ".eps"]);
			}else{
				var rm = spawn("rm", [timestamp + "image" + i + ".png"]);
			}
		}
	}
}
module.exports = router;
