/**
 * Copyright © Volker Schukai and all contributing authors, {{copyRightYear}}. All rights reserved.
 * Node module: @schukai/monster
 *
 * This source code is licensed under the GNU Affero General Public License version 3 (AGPLv3).
 * The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.en.html
 *
 * For those who do not wish to adhere to the AGPLv3, a commercial license is available.
 * Acquiring a commercial license allows you to use this software without complying with the AGPLv3 terms.
 * For more information about purchasing a commercial license, please contact Volker Schukai.
 *
 * SPDX-License-Identifier: AGPL-3.0
 */

import { getGlobalObject } from "../../types/global.mjs";
import { Handler } from "../handler.mjs";
import { LogEntry } from "../logentry.mjs";
import { TRACE, WARN, DEBUG, ERROR, FATAL, INFO } from "../logger.mjs";

export { ConsoleHandler };

/**
 * You can create an object of the class simply by using the namespace `new Monster.Logging.Handler.ConsoleHandler()`.
 *
 * @license AGPLv3
 * @since 1.5.0
 * @copyright Volker Schukai
 * @summary A logging handler that writes Monster log entries to the browser console.
 */
class ConsoleHandler extends Handler {
	/**
	 * This is the central log function. this method must be
	 * overwritten by derived handlers with their own logic.
	 *
	 * ALL > TRACE > DEBUG > INFO > WARN > ERROR > FATAL > OFF  (ALL = 0xff;OFF = 0x00;
	 *
	 * @param {LogEntry} entry
	 * @return {boolean}
	 */
	log(entry) {
		if (super.log(entry)) {
			const console = getGlobalObject("console");
			if (!console) return false;

			if (!console.error) console.error = console.log;
			if (!console.warn) console.warn = console.log;

			switch (entry.getLogLevel()) {
				case TRACE:
				case DEBUG:
				case INFO:
					console.log(entry.toString());
					break;
				case FATAL:
				case ERROR:
					console.error(entry.toString());
					break;
				case WARN:
					console.warn(entry.toString());
					break;
				default:
					console.log(entry.toString());
					break;
			}

			return true;
		}

		return false;
	}
}
