const serverPath = require("./serverPath.js")
const boards = require(serverPath+"/board/boards.js");
//const boards = ["test"]
const filePath = serverPath+"/blog/blogs/";
const fs = require("fs");
const { exec } = require('child_process');

function daysIntoYear(date){
    return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
function secondsIntoDay(time) {
	let hour = time.getUTCHours();
	let minute = time.getUTCMinutes();
	let second = time.getUTCSeconds();
	return ((hour * 3600) + (minute * 60) + second)
}
for (let i = boards.length-1; i >= 0; i--) {
	let comments = require(`${serverPath}/board/${boards[i]}/comments-database.js`);
	console.log(comments);

	let newPageHTML="";
	for (let comment = comments.length-1; comment >= 0; comment--) { 	
		if (typeof comments[comment][2] == 'undefined') {
			newPageHTML+=`<b>${comments[comment][0]}</b>: ${comments[comment][1]}<br/>`
		}
		else {
			let time = new Date(comments[comment][2])
			let second = Math.round((secondsIntoDay(time) / (86400/65536))).toString(16);
			let day = daysIntoYear(time).toString(16);
			let year = time.getUTCFullYear().toString(16);
			newPageHTML+=`[${second} ${day}/${year}] <b>${comments[comment][0]}</b>: ${comments[comment][1]}<br/>`
		}
	}; 
	//newPageHTML = newPageHTML.replace(/|/g,"&vert;")
	//newPageHTML = newPageHTML.replace(/\\/g,"\\\\")
	newPageHTML = newPageHTML.replace(/`/g,"&#96;")
	newPageHTML = newPageHTML.replace(/&/g,"\\&")
	newPageHTML = newPageHTML.replace(/;/g,"\\;")
	newPageHTML = newPageHTML.replace(/'/g,"\\'")
	newPageHTML = newPageHTML.replace(/\*/g,"\\*")
	newPageHTML = newPageHTML.replace(/\n/g," ")
	newPageHTML = newPageHTML.replace(/\r/g," ")
	//console.log(newPageHTML);
	let command = `sed -i 's|<div id="comments" class="${boards[i]}" style="word-wrap: break-word">.*</div><!--comments-->|<div id="comments" class="${boards[i]}" style="word-wrap: break-word">${newPageHTML}</div><!--comments-->|' ${serverPath}/board/${boards[i]}/index.html`;
	//console.log(command)
	exec(command, (error, stdout, stderr) => {
		 if (error) {
		   console.error(`Error: ${error.message}`);
		   return;
		 }
		 else {
			console.log(`Successfully wrote comments to html`)
		 }
	});
};
