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 = "/var/www/html/"
const { exec } = require("child_process");

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

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("/board/submit-comment", (req,res) => {
    	res.redirect(302, req.get("referer"));
	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 :)");
			}
		});
	}
});

app.post("/blog/submit-comment",(req,res) => {
    let jsonString = fs.readFileSync('/var/www/html/blog/comments-database.js', 'utf8');
    let comments = JSON.parse(jsonString);
    res.redirect(302, req.get("referer")); 
    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("/var/www/html/blog/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/blogs/${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('/var/www/html/blog/comments-database.js', jsonString, 'utf8'); 
    }
    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}`);
}); 
