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

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

module.exports = { Logger };
