const express = require('express');
const app = express();
const port = 8003
const path = require("path")
//let comments = require("/srv/www/htdocs/blog/comments.js")
const fs = require("fs")
const validator = require('validator');
const rootPath = require("./serverPath.js");
const { exec } = require("child_process");
const { execSync } = require("child_process");

const escapeHtml = (unsafe) => {
    return unsafe
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;")
	.replace("`", "&#96;")
};

const encode = (unsafe) => {
	console.log(unsafe)
	return unsafe
			// Bold
		.replace(/\*\*(.*?)\*\*/g,'<b>$1</b>')

			// Italics
		.replace(/\*(.*?)\*/g,'<i>$1</i>')

			//links
		.replace(/\[(.*?)\]\(https:\/\/(.*?)\)/g,'<a href="https:\/\/$2">$1</a>')
		.replace(/\[(.*?)\]\(http:\/\/(.*?)\)/g,'<a href="http:\/\/$2">$1</a>')
};

// Middleware to parse URL-encoded and JSON bodies
app.use(express.urlencoded({ extended: true }));
app.use(express.json()); 

app.post("/music/playpause",(req,res) => {
	console.log("toggling pause!")
	exec('echo cycle pause | socat - "/tmp/mpvsocket"');
	res.redirect(302, req.get("referer")); 
});
app.post("/music/next",(req,res) => {
	console.log("skipping to next song")
	exec('echo playlist-next | socat - "/tmp/mpvsocket"')
	setTimeout(function() {
		res.redirect(302, req.get("referer"));
	}, 1000);
});
app.post("/music/prev",(req,res) => {
	console.log("going back to previous song")
	exec('echo playlist-prev | socat - "/tmp/mpvsocket"')
	setTimeout(function() {
		res.redirect(302, req.get("referer"));
	}, 1000);
});

app.post("/maths/submit-topics", (req,res) => {
	console.log("Quesion page")
	console.log(req.body.topic)
	console.log(req.body.subtopic)
	let topic = Number(req.body.topic)
	let subtopic = validator.escape(req.body.subtopic)
	let script = "";
	try {
	    script = execSync(`./maths.sh ${topic} ${subtopic}`, { encoding: 'utf-8' }); // 'utf-8' to get the output as a string
	} catch (error) {
	    console.error('Error executing command:', error);
	}
	output = script.split(/\r?\n/);
	let topic_str = output[0]
	let subtopic_str = output[1]
	let problem = output[2]
	let solution = output[3]
	console.log("Topic: ", topic_str)
	console.log("Subtopic: ", subtopic_str)
	console.log("Problem: ", problem)
	console.log("Solution: ", solution)

	res.send(`<!DOCTYPE html>
		<h1>${topic_str}</h1><br/>
		<h3>${subtopic_str}</h3><br/>
		${problem}
		<form action="/maths/answer" method="post">
			<input type="hidden" name="solution" value="${solution}">
			<input type="hidden" name="topic" value="${topic}">
			<input type="hidden" name="subtopic" value="${subtopic}">
			<button type="submit">Answer</button>
		</form>
		<script>
			MathJax = {
			  tex: {
			    inlineMath: [['$', '$'], ['\\(', '\\)']]
			  }
			};
		</script>
		<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>`)
});

app.post("/maths/answer", (req,res) => {
	console.log("Answer page")
	console.log(req.body.topic)
	console.log(req.body.subtopic)
	let topic = Number(req.body.topic)
	let subtopic = validator.escape(req.body.subtopic)
	res.send(`<!DOCTYPE html>
		<h1>Answer:</h1>
		${req.body.solution}
		<form action="/maths/submit-topics" method="post">
			<input type="hidden" name="topic" value="${topic}">
			<input type="hidden" name="subtopic" value="${subtopic}">
			<button type="submit">Next</button>
		</form>
		<button onclick="window.location.href='https://deadvey.com/maths'">Back</button>
		<script>
			MathJax = {
			  tex: {
			    inlineMath: [['$', '$'], ['\\(', '\\)']]
			  }
			};
		</script>
		<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>`)
});

app.post("/board/submit-comment", (req,res) => {
	let comments = require(`${rootPath}/board/${req.body.pageID}/comments-database.js`)
	let time = new Date().toJSON()
    	console.log(req.get("referer"))
	console.log(comments)
   	if (req.body.comment != "") {
		if (req.body.name == "") {
			req.body.name = "Anonymous";
		}
		comments.push([encode(escapeHtml(req.body.name)),encode(escapeHtml(req.body.comment)),time])
		console.log(comments)
		content = `let comments = ${JSON.stringify(comments)}
		if (typeof module !== "undefined" && module.exports) {
			module.exports = comments;
		}`
		fs.writeFile(`${rootPath}/board/${req.body.pageID}/comments-database.js`, content, (err) => {
			if (err) {
				console.log("Error writing comments to file");
			}
			else {
				console.log("Wrote comments to file :)");
			}
		});
	}
	exec('node write_comments.js', (error, stdout, stderr) => {
	  if (error) {
	    console.error(`Error: ${error.message}`);
	    return;
	  }
	  console.log(`Child script output: ${stdout}`);
	  res.redirect(302, req.get("referer"));
	});
});

app.post("/blog/submit-comment",(req,res) => {
    let jsonString = fs.readFileSync(`${rootPath}/blogs/comments-database.js`, 'utf8');
    let comments = JSON.parse(jsonString);
    console.log(req.get("referer"))
    console.log(req.body.name)
    if (req.body.comment !="") {
	if (req.body.name == "") {
	    req.body.name = "Anonymous";
	}
	comments[req.body.pageID].push([encode(escapeHtml(req.body.name)),encode(escapeHtml(req.body.comment))])
	content=`comments=${JSON.stringify(comments)}
if (typeof module !== "undefined" && module.exports) {
                module.exports = comments;     
}`
	fs.writeFile(`${rootPath}/blogs/comments.js`, content, (err) => {
	    if (err) { 
		console.error('Error creating file:', err);  
	    } else {
		console.log('File created written: comments.js'); 
	    } 
	});
	motd_content = `
!ALERT!
${escapeHtml(req.body.name)} Commented:
${escapeHtml(req.body.comment)}
on the blog: https://deadvey.com/blog/${req.body.pageID}.html

`
	fs.writeFile("/etc/motd", motd_content, (err) => {
	    if (err) { 
		console.error('Error creating file:', err);  
	    } else {
		console.log('File created written: Comments.js'); 
	    } 
	});
	const jsonString = JSON.stringify(comments);
	fs.writeFileSync(`${rootPath}/blogs/comments-database.js`, jsonString, 'utf8'); 
    }
    exec('node makeblogs.js', (error, stdout, stderr) => {
	  if (error) {
	    console.error(`Error: ${error.message}`);
	    return;
	  }
	  console.log(`Child script output: ${stdout}`);
	  res.redirect(302, req.get("referer"));
	});

    console.log(comments) 
});

app.use(express.static(rootPath)); 

// Start the server
app.listen(port, () => {
  console.log(`Server is running at 
http://localhost:${port}
in directory: ${rootPath}`);
}); 
