/* ----------------------------------------------------------------------------    

 Question Server
 GitLab: <https://gitlab.com/YourFriendlyNeighborhoodDealer/question-node-server>

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see <https://www.gnu.org/licenses/>.

 ------------------------------------------------------------------------- */

var express = require('express');
var bodyParser = require('body-parser');
var busboy = require('connect-busboy');
var fs = require('fs');
var app = express();
var http = require('http');
var https = require('https');

var logger = require('./logger.js');
var utils = require('./utils.js');
var actions = require('./actions.js');
var stat = require('./stat.js');

var bodyParser = require('body-parser');

const recivedFiles = "public/recivedfiles";
const motdFile = "public/motd";
const staticFile = "public/data/static";
const dataFile = "public/data.json";
const countFile = "public/data/count";
const manFile = "public/man.html";
const simpOutFile = "public/simplified";
const inputFile = "stats/inputs";
const msgFile = "stats/msgs";
const logFile = "stats/logs";

// https://certbot.eff.org/
const key = fs.readFileSync("/etc/letsencrypt/live/questionmining.tk/privkey.pem", "utf8");
const cert = fs.readFileSync("/etc/letsencrypt/live/questionmining.tk/fullchain.pem", "utf8");
const ca = fs.readFileSync("/etc/letsencrypt/live/questionmining.tk/chain.pem", "utf8");
var certs = {key:key, cert:cert, ca:ca};
const port = 8080;
const httpsPort = 8443;

var highlights = ["public", "static", "manual", "isgetting", "postfeedback",
	"postquestions"
];

var newMessages = "";

app.set('view engine', 'ejs');
//app.all('*', function(req, res, next) {
//	if(req.secure) {
//		next();
//	} else {
//		res.redirect('https://' + req.hostname + req.url); 
//	}
//});
app.use(function(req, res, next) {
	res.on('finish', function() {
		Log(req, true, res.statusCode);
		if (res.statusCode != 404)
			stat.LogStat(req.url);
	});
	next();
});
app.use(express.static('public'));
app.use(busboy({
	limits: {
		fileSize: 10 * 1024 * 1024
	}
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	limit: '5mb',
	extended: true
}));
app.use(bodyParser.json({
	limit: '5mb'
}));

app.get('/', function(req, res) {
	res.render('main', {
		sdata: utils.ReadFile(staticFile)
	});
	res.end();
});

app.get('/manual', function(req, res) {
	res.write(utils.ReadFile(manFile));
	res.end();
});

app.get('/public', function(req, res) {
	var response = '@' + utils.ReadFile(motdFile);
	response += utils.ReadFile(staticFile);
	res.write(response);
	res.end();
});

app.get('/static', function(req, res) {
	var response = '@' + utils.ReadFile(motdFile);
	response += utils.ReadFile(staticFile);
	res.write(response);
	res.end();
});

app.get('/legacy', function(req, res) {
	// TODO: make this ejs
	var f = utils.ReadFile(dataFile);
	var r = '<html><body bgcolor="#212127"><head><meta charset="UTF-8">';
	r += '<style>body { font: normal 14px Verdana; color: #999999;}</style>';
	var d = actions.LoadJSON(f).toString().split("\n");
	for (var i = 0; i < d.length; i++)
		r += d[i] + "</br>";
	r += '</head></body></html>';

	res.write(r);
	res.end();
});

app.post('/postfeedback', function(req, res) {
	res.redirect('back');
	newMessages += "\n" + req.body.message_field;
	logger.Log("[UMSG]: " + req.body.message_field, logger.GetColor("bluebg"), true);
	utils.AppendToFile(logger.GetDateString() + ": " + req.body.message_field, msgFile);
});

app.get('/postfeedback', function(req, res) {
	res.render('main', {
		sdata: utils.ReadFile(staticFile)
	});
});

app.post('/isAdding', function(req, res) {
	res.end('OK');
	Log(req);
	actions.ProcessIncomingRequest(req.body.datatoadd);
	utils.WriteBackup();
});

app.get('/sanityCheck', function(req, res) {
	res.end('Hello guys');
});

app.get('/menuClick', function(req, res) {
	res.redirect("/");
	res.end();
});

app.route('/badtestsender').post(function(req, res, next) {
	var fstream;
	req.pipe(req.busboy);
	req.busboy.on('file', function(fieldname, file, filename) {
		logger.Log("[UPL]: Uploading: " + filename, logger.GetColor("blue"));

		fstream = fs.createWriteStream(recivedFiles + "/" + filename + " | " + Date().toString());
		file.pipe(fstream);
		fstream.on('close', function() {
			logger.Log("[UPL]: Upload Finished of " + filename, logger.GetColor("blue"));
			res.render("uploaded");
		});
		fstream.on('error', function(err) {
			console.log("ERROR:" + err);
			res.end("file uploaded");
		});
	});
});

app.get('/sanityCheck', function(req, res) {
	res.end('Uploaded :) go back now');
});

app.get('/scriptgit', function(req, res) {
	res.redirect("https://gitlab.com/YourFriendlyNeighborhoodDealer/moodle-test-userscript");
	res.end();
});

app.get('/servergit', function(req, res) {
	res.redirect("https://gitlab.com/YourFriendlyNeighborhoodDealer/question-node-server");
	res.end();
});

app.get('*', function(req, res) {
	res.render('404');
	res.status(404);
	// utils.AppendToFile(logger.GetDateString() + ": " + "404 GET", logFile);
});

app.post('*', function(req, res) {
	res.status(404);
	// utils.AppendToFile(logger.GetDateString() + ": " + "404 POST", logFile);
});

stat.Load();
const httpServer = http.createServer(app);
const httpsServer = https.createServer(certs, app);
httpServer.listen(port);
httpsServer.listen(httpsPort);
logger.Log("[STRT]: Server listening on port " + port + " (http), and " + httpsPort + " (https)...", logger.GetColor("yellow"));

function Log(req, toFile, sc) {
	try {
		var ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress;
		var logEntry = "[RSND]: " + ip + ", " + req.headers['user-agent'] +
			" " + req.method + " ";
		if (sc == 404)
			logEntry += sc + " ";
		logEntry += req.url;
		var color = logger.GetColor("green");
		for (var i = 0; i < highlights.length; i++)
			if (req.url.toLowerCase().includes(highlights[i])) {
				color = logger.GetColor("blue");
				break;
			}
		if (req.url.toLowerCase().includes("isadding"))
			color = logger.GetColor("yellow");
		if (!toFile) {
			logger.Log(logEntry, color);
		} else {
			var defLogs = logger.GetDateString() + ": " + logEntry;
			var extraLogs = "\n\t" + JSON.stringify(req.headers) + "\n\t" + JSON.stringify(req
					.body) + "\n";

			utils.AppendToFile(defLogs, logFile);
		}

	} catch (e) {
		logger.Log("Error at logging lol", logger.GetColor("redbg"), true);
	}
}