package cn.citycraft.AuthMe;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.message.Message;

/**
 *
 * @author Xephi59
 */
public class Log4JFilter implements org.apache.logging.log4j.core.Filter {

	public Log4JFilter() {
	}

	@Override
	public Result filter(final LogEvent record) {
		try {
			if (record == null || record.getMessage() == null) {
				return Result.NEUTRAL;
			}
			final String logM = record.getMessage().getFormattedMessage().toLowerCase();
			return isLogger(logM);
		} catch (final NullPointerException npe) {
			return Result.NEUTRAL;
		}
	}

	@Override
	public Result filter(final Logger arg0, final Level arg1, final Marker arg2, final Message message, final Throwable arg4) {
		try {
			if (message == null) {
				return Result.NEUTRAL;
			}
			final String logM = message.getFormattedMessage().toLowerCase();
			return isLogger(logM);
		} catch (final NullPointerException npe) {
			return Result.NEUTRAL;
		}
	}

	@Override
	public Result filter(final Logger arg0, final Level arg1, final Marker arg2, final Object message, final Throwable arg4) {
		try {
			if (message == null) {
				return Result.NEUTRAL;
			}
			final String logM = message.toString().toLowerCase();
			return isLogger(logM);
		} catch (final NullPointerException npe) {
			return Result.NEUTRAL;
		}
	}

	@Override
	public Result filter(final Logger arg0, final Level arg1, final Marker arg2, final String message, final Object... arg4) {
		try {
			if (message == null) {
				return Result.NEUTRAL;
			}
			final String logM = message.toLowerCase();
			return isLogger(logM);
		} catch (final NullPointerException npe) {
			return Result.NEUTRAL;
		}
	}

	@Override
	public Result getOnMatch() {
		return Result.NEUTRAL;
	}

	@Override
	public Result getOnMismatch() {
		return Result.NEUTRAL;
	}

	private Result isLogger(final String logM) {
		if (!logM.contains("issued server command:")) {
			return Result.NEUTRAL;
		}
		if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") && !logM.contains("/authme register ")
				&& !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") && !logM.contains("/register ")) {
			return Result.NEUTRAL;
		}
		return Result.DENY;
	}

}
