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

 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/>.

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

module.exports = {
	ProcessIncomingRequest: ProcessIncomingRequest,
	CheckData: CheckData
};

var recievedFile = "stats/recieved";
var publicFile = "public/data/public";
var staticFile = "public/data/static";
var manFile = "public/man.html";

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

function Process(d, file) {
	logger.Log("[PCES]: File: " + file);

	try {

		if (d.data.split("\n").length > 1) {
			var oldFile = utils.ReadFile(file);
			var newFile = oldFile + "\n+" + d.data;

			var newRes = CheckData(newFile);
			var oldRes = CheckData(oldFile);

			if (newRes.count > 0)
				logger.Log("[NLOD]: new file result: " + newRes.count, logger.GetColor("blue"));
			else
				logger.Log("[NLOD]: new file NLOD error, " + newRes.log, logger.GetColor("redbg"), true);

			if (oldRes.count > 0)
				logger.Log("[NLOD]: old public result: " + oldRes.count, logger.GetColor("blue"));
			else
				logger.Log("[NLOD]: old public NLOD error, " + oldRes.log, logger.GetColor("redbg"), true);

			utils.WriteFile(newFile, file);
			logger.Log("[NLOD]: New data written to: " + file);

			return newRes.count - oldRes.count;
		} else
			logger.Log("[PCES]: No new data.");


	} catch (e) {
		Beep();
		logger.Log("[ERR ]: Error at processing data! File: " + file, logger.GetColor("redbg"));
		logger.Log(e.toString(), logger.GetColor("redbg"));
	}
	return -1;
}

function ProcessIncomingRequest(data) {

	if (data == undefined) {
		logger.Log("[PCES]: Recieved data is undefined!", logger.GetColor("redbg"));
		return;
	}

	var d = SetupData(data);

	logger.Log("[PCES]: Processing data: " + d.subj + " (" + d.type + ")");
	if (d.subj == undefined){
		logger.Log(JSON.stringify(d), logger.GetColor("red"));
		return;
	}

	var newItems = 0;

	/*if (d.type == 0) // -> safe, static
		newItems = Process(d, staticFile);
	else if (d.type == 1) // -> unsafe, public
		newItems = Process(d, publicFile);
	else { // -> error, or old client
		logger.Log("[PCES]: Old client...");
		Process(d, publicFile);
		Process(d, staticFile);
	}*/
	try {
		var splitted = d.alldata.split("\n");
		var count = 0;
		for (var i = 0; i < splitted.length; i++)
			if (splitted[i][0] == '?')
				count ++;
		logger.Log("[PCES]: Test all question count: " + count, logger.GetColor("blue"));
	} catch (e) {console.log("Error :c"); console.log(e);}
	var newPubItems = Process(d, publicFile);
	var newStatItems = Process(d, staticFile);

	utils.AppendToFile(logger.GetDateString() + "\n" + d.data, recievedFile);
	PrintNewCount(d, newPubItems, publicFile);
	PrintNewCount(d, newStatItems, staticFile);
}

function PrintNewCount(d, newItems, file) {
	if (newItems > 0) {
		var count = 0;
		var splitted = d.alldata.split("\n");
		for (var i = 0; i < splitted.length; i++)
			if (splitted[i].startsWith("?"))
				count++;
		logger.Log("[NEW ]: " + file + " All / New: " + count + " / " + newItems, logger.GetColor("cyan"));
	}
}

function SetupData(data) {
	var pdata = data.split("<#>");
	if (pdata.length <= 0)
		throw "No data recieved!";
	var d = {}; // parsed data
	for (var i = 0; i < pdata.length; i++) {
		var td = pdata[i].split("<=>");
		if (td.length == 2)
			d[td[0]] = td[1];
		else
			throw "Invalid parameter recieved!";
	}
	return d;
}

function CheckData(data) {
	try {
		var presult = NLoad(data);
		return presult;
	} catch (e) {
		logger.Log("[NLOD]: NLOD error, " + e.toString(), logger.GetColor("redbg"), true);
		return {
			count: -1,
			log: [e.toString()]
		};
	}
}

function NLoad(resource) {
	var resultLog = [];
	var count = -1;
	var allCount = 0;
	if (resource == undefined)
		throw "A megadott adat undefined!";
	resource = resource.split("\n"); // splitting by enters
	if (resource.length == 1)
		throw "A megadott adat nem sorokból áll!";
	var data = []; // initializing data declared at the begining

	function AddNewSubj(name) // adds a new subject to the data
	{
		data.push({
			"questions": []
		}); // ads aa new object, with an empty array in it
		GetCurrSubj().name = name; // sets the name for it
		GetCurrSubj().count = 0; // setting count to default
		// setting if its active only if its undefined, otherwise previous user setting shouldt be overwritten
	}

	function AddItem() // adds an item to the last subjects questions
	{
		GetCurrSubj().count++;
		allCount++; // incrementing all count
		GetCurrSubj().questions.push({}); // adding a new empty object to the last item in the data
	}

	function GetLastItem() // returns the last item of the last item of data
	{
		var q = GetCurrSubj().questions.length; // questions length
		return GetCurrSubj().questions[q - 1];
	}

	function GetCurrSubj() {
		return data[data.length - 1];
	}

	// ? : question
	// ! : answer
	// > : image JSON data
	// + : subject name

	// checking for name
	for (var j = 0; j < resource.length; j++) // goes through resources
	{
		if (resource[j][0] == '+') // if there is a name identifier
		{
			break; // breaks, couse there will be a name
		}
		if (resource[j][0] == '?' || resource[j][0] == '!' || resource[j][0] == '>') // if it begins with another identifier:
		{
			AddNewSubj("NONAME"); // there is no name (for the first question at least), so setting it noname.
			break;
		}
		// else it does nothing, continues to check
	}
	var jumped = 0; // the amount of lines it processed
	for (var i = 0; i < resource.length; i += jumped) // gouing through the resource
	{
		jumped = 0; // resetting it to 0
		var currRawDataQ = resource[i]; // current question
		var currRawDataA = resource[i + 1]; // current answer
		var currRawDataI = resource[i + 2]; // current image
		if (currRawDataQ != undefined && currRawDataQ[0] == '?' && currRawDataA != undefined &&
			currRawDataA[0] == '!') // if the current line is ? and the next is ! its a data
		{
			AddItem();
			GetLastItem().q = currRawDataQ.substr(1);
			GetLastItem().a = currRawDataA.substr(1);
			jumped += 2;
			if (currRawDataI != undefined && currRawDataI[0] == '>') {
				GetLastItem().i = currRawDataI.substr(1);
				jumped++;
			}
		} else if (currRawDataQ[0] == '+') // if its a new subject
		{
			AddNewSubj(currRawDataQ.substr(1));
			jumped++;
		} else {
			// this should be invalid question order
			resultLog.push("Warning @ line " + i + ":" + currRawDataQ + " " + currRawDataA + " " +
				currRawDataI);
			jumped++;
		}
	} // end of parsing all data
	return {
		count: allCount,
		log: resultLog
	};
}