const EventEmitter = require('events');
const fs = require("fs");
const md5 = require('md5');

let logger = {
	log: (...p) => console.log(...p),
	error: (msg, err, level) => console.error(`Error: ${msg}\n${"=".repeat(16)}\nStack Error >>`, err.stack)
};
let fileMD5;
global.config = {};
let emitterObject = new EventEmitter();

function configValidator (cfg) {
	// Any custom validation
	// must be return: { condition : bool, fineConfig : confg }
	return {
		condition: true,
		fineConfig: cfg
	};
}

function setConfig (configData, isFirst = true) {
	try {
		fileMD5 = md5(configData);
		if (!isFirst)
			emitterObject.emit("config.update", {
				oldConfig: Object.assign({}, global.config),
				newConfig: JSON.parse(configData)
			});
		global.config = Object.assign({}, JSON.parse(configData));
		const result = configValidator(Object.assign({}, global.config));
		if (result.condition) {
			global.config = result.fineConfig;
		}
		/*if (!config?.ip) config.ip = "0.0.0.0";
		if (!config?.port) config.port = 1441;
		else config.port = +config.port;*/
	}
	catch (err) {
		logger.error("Config not parsed", err, "config-parse");
	}
}

module.exports = (emitter, configObject, loggerObj = logger) => {
	emitterObject = emitter;
	global.config = configObject;
	logger = loggerObj ?? logger;

	setConfig(fs.readFileSync("./config.json", { encoding: 'utf-8' }));

	// Every time checking config.json for rt-update
	setInterval(async () => {
		fs.readFile("./config.json", { encoding: 'utf-8' }, (err, data) => {
			if (err) {
				logger.error("Config not readable", err, "config-file");
			}
			else {
				if (fileMD5 !== md5(data)) {
					logger.log("Changes on file config.json detected: config will be reloaded");
					setConfig(data, false);
				}
			}
		});
	}, 5);
}
