package cn.citycraft.AuthMe.listener;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerListPingEvent;

import cn.citycraft.AuthMe.AuthMe;
import cn.citycraft.AuthMe.ConsoleLogger;
import cn.citycraft.AuthMe.Utils;
import cn.citycraft.AuthMe.settings.Messages;
import cn.citycraft.AuthMe.settings.Settings;

public class AuthMeServerListener implements Listener {

	public AuthMe plugin;
	private final Messages m = Messages.getInstance();

	public AuthMeServerListener(final AuthMe plugin) {
		this.plugin = plugin;
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onPluginDisable(final PluginDisableEvent event) {
		final String pluginName = event.getPlugin().getName();
		if (pluginName.equalsIgnoreCase("Essentials")) {
			plugin.ess = null;
			ConsoleLogger.info("Essentials has been disabled, unhook!");
			return;
		}
		if (pluginName.equalsIgnoreCase("EssentialsSpawn")) {
			plugin.essentialsSpawn = null;
			ConsoleLogger.info("EssentialsSpawn has been disabled, unhook!");
			return;
		}
		if (pluginName.equalsIgnoreCase("Vault")) {
			plugin.permission = null;
			ConsoleLogger.showError("Vault has been disabled, unhook permissions!");
		}
		if (pluginName.equalsIgnoreCase("ProtocolLib")) {
			plugin.inventoryProtector = null;
			ConsoleLogger.showError("ProtocolLib has been disabled, unhook packet inventory protection!");
		}
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onPluginEnable(final PluginEnableEvent event) {
		final String pluginName = event.getPlugin().getName();
		if (pluginName.equalsIgnoreCase("Essentials") || pluginName.equalsIgnoreCase("EssentialsSpawn")) {
			plugin.checkEssentials();
		}
		if (pluginName.equalsIgnoreCase("Vault")) {
			plugin.checkVault();
		}
		if (pluginName.equalsIgnoreCase("ProtocolLib")) {
			plugin.checkProtocolLib();
		}
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onServerPing(final ServerListPingEvent event) {
		if (!Settings.enableProtection) {
			return;
		}
		if (Settings.countries.isEmpty()) {
			return;
		}
		if (!Settings.countriesBlacklist.isEmpty()) {
			if (Settings.countriesBlacklist.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) {
				event.setMotd(m.send("country_banned")[0]);
			}
		}
		if (Settings.countries.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) {
			event.setMotd(plugin.getServer().getMotd());
		} else {
			event.setMotd(m.send("country_banned")[0]);
		}
	}
}
