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 {
	String[] filterkey = new String[] { "/login ", "/l ", "/reg ", "/register ", "/changepassword ", "/unregister ", "/authme register ", "/authme changepassword ", "/authme reg ", "/authme cp " };

	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();
			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();
			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();
			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;
			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) {
		final String log = logM.toLowerCase();
		if (!log.contains("issued server command:")) {
			return Result.NEUTRAL;
		}
		for (final String key : filterkey) {
			if (log.contains(key)) {
				final String playername = logM.split(" ")[0];
				AuthMe.getInstance().getLogger().info(playername + " 执行了一个 AuthMe 命令!");
				return Result.DENY;
			}
		}
		return Result.NEUTRAL;
	}

}
