/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef POLYGUN_UTILS_LOGGER_HPP
#define POLYGUN_UTILS_LOGGER_HPP

#include <cstdio>
#include <cstdarg>
#include <mutex>

namespace polygun::utils {
	class Logger final {
	public:
		Logger(bool output_to_file, bool enable_verbose);
		~Logger();

		void info(const char* file, size_t line, const char* fmt, ...);
		void warning(const char* file, size_t line, const char* fmt, ...);
		void error(const char* file, size_t line, const char* fmt, ...);
		void fatal(const char* file, size_t line, const char* fmt, ...);
		void verbose(const char* file, size_t line, const char* fmt, ...);

		static Logger& get() { return *s_instance; }
		static void create(bool output_to_file, bool enable_verbose);
		static void cleanup() { delete s_instance; }

	private:
		bool m_output_to_file, m_enable_verbose;
		FILE* m_output_file;
		std::mutex m_access_mutex;
		static Logger* s_instance;

	private:
		void print_internal(FILE* output, const char* color, const char* mode, const char* file, size_t line, const char* fmt, va_list args);
	};
}

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#endif
#define LOG_INFO(fmt, ...) polygun::utils::Logger::get().info(__FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_WARNING(fmt, ...) polygun::utils::Logger::get().warning(__FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_ERROR(fmt, ...) polygun::utils::Logger::get().error(__FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_FATAL(fmt, ...) polygun::utils::Logger::get().fatal(__FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define LOG_VERBOSE(fmt, ...) polygun::utils::Logger::get().verbose(__FILE__, __LINE__, fmt, ##__VA_ARGS__)
#if defined(__clang__)
#pragma clang diagnostic pop
#endif

#endif // POLYGUN_UTILS_LOGGER_HPP
