const config = require("./config-handler");
const fs = require("fs");

class Logger {
	constructor () {
		this.logId = `${(new Date()).getTime()}`;
		let loggerFolder = config().logger_folder;
		loggerFolder = !["/", "\\"].includes(loggerFolder.at(-1))
			? loggerFolder + "/"
			: loggerFolder;
		fs.writeFile(
			`${loggerFolder}${this.logId}.log`, '',
			{
				encoding: "utf8"
			}
			(err) => {
				throw err;
			}
		);
	}
	
	log (date, ip, action, isError = false) {
		fs.writeFile(
			`${loggerFolder}${this.logId}.log`, !isError ? `IP: ${ip}\nДата запроса: ${date}` : `\nПроизошла ошибка: ${action}`,
			{
				encoding : "utf8",
				flag     : "a"
			}
			(err) => {
				throw err;
			}
		);
	}
}

module.exports = async (req, res, next) => { Logger };