package cn.citycraft.AuthMe;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;

import com.earth2me.essentials.Essentials;

import cn.citycraft.AuthMe.cache.auth.PlayerAuth;
import cn.citycraft.AuthMe.cache.auth.PlayerCache;
import cn.citycraft.AuthMe.cache.backup.JsonCache;
import cn.citycraft.AuthMe.cache.limbo.LimboCache;
import cn.citycraft.AuthMe.cache.limbo.LimboPlayer;
import cn.citycraft.AuthMe.commands.AdminCommand;
import cn.citycraft.AuthMe.commands.CaptchaCommand;
import cn.citycraft.AuthMe.commands.ChangePasswordCommand;
import cn.citycraft.AuthMe.commands.ConverterCommand;
import cn.citycraft.AuthMe.commands.LoginCommand;
import cn.citycraft.AuthMe.commands.LogoutCommand;
import cn.citycraft.AuthMe.commands.RegisterCommand;
import cn.citycraft.AuthMe.commands.UnregisterCommand;
import cn.citycraft.AuthMe.converter.Converter;
import cn.citycraft.AuthMe.converter.ForceFlatToSqlite;
import cn.citycraft.AuthMe.datasource.CacheDataSource;
import cn.citycraft.AuthMe.datasource.DataSource;
import cn.citycraft.AuthMe.datasource.DatabaseCalls;
import cn.citycraft.AuthMe.datasource.FlatFile;
import cn.citycraft.AuthMe.datasource.MySQL;
import cn.citycraft.AuthMe.datasource.SQLite;
import cn.citycraft.AuthMe.datasource.SQLite_HIKARI;
import cn.citycraft.AuthMe.listener.AuthMeBlockListener;
import cn.citycraft.AuthMe.listener.AuthMeEntityListener;
import cn.citycraft.AuthMe.listener.AuthMeInventoryPacketAdapter;
import cn.citycraft.AuthMe.listener.AuthMePlayerListener;
import cn.citycraft.AuthMe.listener.AuthMePlayerListener16;
import cn.citycraft.AuthMe.listener.AuthMePlayerListener18;
import cn.citycraft.AuthMe.listener.AuthMeServerListener;
import cn.citycraft.AuthMe.plugin.manager.BungeeCordMessage;
import cn.citycraft.AuthMe.plugin.manager.EssSpawn;
import cn.citycraft.AuthMe.process.Management;
import cn.citycraft.AuthMe.settings.Messages;
import cn.citycraft.AuthMe.settings.OtherAccounts;
import cn.citycraft.AuthMe.settings.Settings;
import cn.citycraft.AuthMe.settings.Spawn;
import cn.citycraft.PluginHelper.config.FileConfig;
import cn.citycraft.PluginHelper.utils.VersionChecker;
import fr.xephi.authme.api.API;
import fr.xephi.authme.api.NewAPI;
import net.milkbowl.vault.permission.Permission;

public class AuthMe extends JavaPlugin {

	private static AuthMe authme;
	private static Server server;
	public boolean antibotMod = false;

	public NewAPI api;
	public ConcurrentHashMap<String, String> cap = new ConcurrentHashMap<>();
	public ConcurrentHashMap<String, Integer> captcha = new ConcurrentHashMap<>();
	public FileConfig config;
	public DataSource database;
	public DataManager dataManager;
	public boolean delayedAntiBot = true;
	public Essentials ess;
	public Location essentialsSpawn;
	public AuthMeInventoryPacketAdapter inventoryProtector;
	public Management management;
	public OtherAccounts otherAccounts;

	public Permission permission;

	public ConcurrentHashMap<String, String> realIp = new ConcurrentHashMap<>();

	// TODO: Create Manager for fields below
	public ConcurrentHashMap<String, BukkitTask> sessions = new ConcurrentHashMap<>();

	private Logger authmeLogger;
	private Messages m;
	private JsonCache playerBackup;

	private Settings settings;

	public static AuthMe getInstance() {
		return authme;
	}

	public boolean authmePermissible(final CommandSender sender, final String perm) {
		if (sender.hasPermission(perm)) {
			return true;
		} else if (permission != null) {
			return permission.has(sender, perm);
		}
		return false;
	}

	// Check if a player/command sender have a permission
	public boolean authmePermissible(final Player player, final String perm) {
		if (player.hasPermission(perm)) {
			return true;
		} else if (permission != null) {
			return permission.playerHas(player, perm);
		}
		return false;
	}

	// Get the Essentials plugin
	public void checkEssentials() {
		if (server.getPluginManager().isPluginEnabled("Essentials")) {
			try {
				ess = (Essentials) server.getPluginManager().getPlugin("Essentials");
				ConsoleLogger.info("发现 Essentials 启用相关功能...");
			} catch (Exception | NoClassDefFoundError ingnored) {
				ess = null;
			}
		} else {
			ess = null;
		}
		if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) {
			try {
				essentialsSpawn = new EssSpawn().getLocation();
				ConsoleLogger.info("发现 EssentialsSpawn 读取重生点...");
			} catch (final Exception e) {
				essentialsSpawn = null;
				ConsoleLogger.showError("无法读取文件 /plugins/Essentials/spawn.yml !");
			}
		} else {
			essentialsSpawn = null;
		}
	}

	// Check the presence of the ProtocolLib plugin
	public void checkProtocolLib() {
		if (Settings.protectInventoryBeforeLogInEnabled) {
			if (server.getPluginManager().isPluginEnabled("ProtocolLib")) {
				inventoryProtector = new AuthMeInventoryPacketAdapter(this);
				inventoryProtector.register();
			} else {
				ConsoleLogger.showError("警告!!! 服务器内未找到 ProtocolLib 插件 关闭背包保护功能...");
				Settings.protectInventoryBeforeLogInEnabled = false;
			}
		}
	}

	// Check the presence of the Vault plugin and a permissions provider
	public void checkVault() {
		if (server.getPluginManager().isPluginEnabled("Vault")) {
			final RegisteredServiceProvider<Permission> permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
			if (permissionProvider != null) {
				permission = permissionProvider.getProvider();
				ConsoleLogger.info("发现 Vault 使用权限系统: " + permission.getName());
			} else {
				ConsoleLogger.showError("发现 Vault, 但是 Vault 未找到权限系统...");
			}
		} else {
			permission = null;
		}
	}

	// Select the player to kick when a vip player join the server when full
	public Player generateKickPlayer(final Collection<? extends Player> collection) {
		Player player = null;
		for (final Player p : collection) {
			if (!(authmePermissible(p, "authme.vip"))) {
				player = p;
				break;
			}
		}
		return player;
	}

	@Override
	public FileConfiguration getConfig() {
		if (config == null) {
			config = new FileConfig(this);
		}
		return config;
	}

	@Deprecated
	public String getCountryCode(final String ip) {
		return Utils.getCountryCode(ip);
	}

	@Deprecated
	public String getCountryName(final String ip) {
		return Utils.getCountryName(ip);
	}

	public String getIP(final Player player) {
		final String name = player.getName().toLowerCase();
		String ip = player.getAddress().getAddress().getHostAddress();
		if (Settings.bungee) {
			if (realIp.containsKey(name)) {
				ip = realIp.get(name);
			}
		}
		return ip;
	}

	public Messages getMessages() {
		return m;
	}

	public Settings getSettings() {
		return settings;
	}

	// Return the spawn location of a player
	public Location getSpawnLocation(final Player player) {
		final World world = player.getWorld();
		final String[] spawnPriority = Settings.spawnPriority.split(",");
		Location spawnLoc = world.getSpawnLocation();
		for (int i = spawnPriority.length - 1; i >= 0; i--) {
			final String s = spawnPriority[i];
			if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) {
				spawnLoc = getDefaultSpawn(world);
			}
			if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null) {
				spawnLoc = getEssentialsSpawn();
			}
			if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) {
				spawnLoc = getAuthMeSpawn(player);
			}
		}
		if (spawnLoc == null) {
			spawnLoc = world.getSpawnLocation();
		}
		return spawnLoc;
	}

	public boolean hasJoinedIp(final String name, final String ip) {
		int count = 0;
		for (final Player player : Utils.getOnlinePlayers()) {
			if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name)) {
				count++;
			}
		}
		return count >= Settings.getMaxJoinPerIp;
	}

	public boolean isLoggedIp(final String name, final String ip) {
		int count = 0;
		for (final Player player : Utils.getOnlinePlayers()) {
			if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) {
				count++;
			}
		}
		return count >= Settings.getMaxLoginPerIp;
	}

	@Override
	public void onDisable() {
		// Save player data
		final Collection<? extends Player> players = Utils.getOnlinePlayers();
		if (players != null) {
			for (final Player player : players) {
				this.savePlayer(player);
			}
		}

		// Close the database
		if (database != null) {
			database.close();
		}

		// Do backup on stop if enabled
		if (Settings.isBackupActivated && Settings.isBackupOnStop) {
			final boolean Backup = new PerformBackup(this).doBackup();
			if (Backup) {
				ConsoleLogger.info("数据文件备份完成.");
			} else {
				ConsoleLogger.showError("备份数据文件时发生错误 备份失败!");
			}
		}

		// Disabled correctly
		ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " 已卸载!");
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onEnable() {
		// Set the Instance
		server = getServer();
		authmeLogger = Logger.getLogger("AuthMe");
		authme = this;

		final PluginManager pm = server.getPluginManager();

		// Setup the Logger
		if (authmeLogger == null) {
			authmeLogger = this.getLogger();
		} else {
			authmeLogger.setParent(this.getLogger());
		}

		// Load settings and custom configurations
		// TODO: new configuration style (more files)
		try {
			settings = new Settings(this);
			Settings.reloadcfg();
			Settings.loadVariables();
		} catch (final Exception e) {
			ConsoleLogger.writeStackTrace(e);
			ConsoleLogger.showError("无法载入配置文件... 某些配置是错误的, 为了安全考虑 服务器即将关闭!");
			try {
				Thread.sleep(3000);
			} catch (final InterruptedException e1) {
			}
			server.shutdown();
			return;
		}

		// Setup otherAccounts file
		otherAccounts = OtherAccounts.getInstance();

		// Setup messages
		m = Messages.getInstance();

		// Set Console Filter
		if (Settings.removePassword) {
			final ConsoleFilter filter = new ConsoleFilter();
			this.getLogger().setFilter(filter);
			Bukkit.getLogger().setFilter(filter);
			Logger.getLogger("Minecraft").setFilter(filter);
			authmeLogger.setFilter(filter);
			// Set Log4J Filter
			try {
				Class.forName("org.apache.logging.log4j.core.Filter");
				setLog4JFilter();
			} catch (ClassNotFoundException | NoClassDefFoundError e) {
				ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
			}
			ConsoleLogger.info("已开启密码安全替换 控制台将不会记录密码相关数据...");
		}

		// AntiBot delay
		if (Settings.enableAntiBot) {
			Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
				@Override
				public void run() {
					delayedAntiBot = false;
				}
			}, 2400);
		}

		// Download GeoIp.dat file
		Utils.checkGeoIP();

		// Find Permissions
		checkVault();

		// Check Essentials
		checkEssentials();

		// Check if the protocollib is available. If so we could listen for
		// inventory protection
		checkProtocolLib();

		// Do backup on start if enabled
		if (Settings.isBackupActivated && Settings.isBackupOnStart) {
			// Do backup and check return value!
			if (new PerformBackup(this).doBackup()) {
				ConsoleLogger.info("数据备份完成...");
			} else {
				ConsoleLogger.showError("备份数据文件时发生错误 备份失败!");
			}
		}

		// Connect to the database and setup tables
		try {
			setupDatabase();
		} catch (final Exception e) {
			ConsoleLogger.writeStackTrace(e);
			ConsoleLogger.showError(e.getMessage());
			ConsoleLogger.showError("连接数据库期间发生错误! Authme 初始化被中断!");
			stopOrUnload();
			return;
		}

		// Setup the inventory backup
		playerBackup = new JsonCache();

		// Set the DataManager
		dataManager = new DataManager(this);

		// Setup the new API
		api = new NewAPI(this);
		// Setup the old deprecated API
		new API(this);

		// Setup Management
		management = new Management(this);

		// Bungeecord hook
		if (Settings.bungee) {
			ConsoleLogger.info("已启用 BungeeCord 数据转发...");
			Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
			Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this));
		}

		// Reload support hook
		if (Settings.reloadSupport) {
			if (database != null) {
				final int playersOnline = Utils.getOnlinePlayers().size();
				if (playersOnline < 1) {
					database.purgeLogged();
				} else {
					for (final PlayerAuth auth : database.getLoggedPlayers()) {
						if (auth == null) {
							continue;
						}
						auth.setLastLogin(new Date().getTime());
						database.updateSession(auth);
						PlayerCache.getInstance().addPlayer(auth);
					}
				}
			}
		}

		// Register events
		pm.registerEvents(new AuthMePlayerListener(this), this);
		// Try to register 1.6 player listeners
		try {
			Class.forName("org.bukkit.event.player.PlayerEditBookEvent");
			pm.registerEvents(new AuthMePlayerListener16(this), this);
		} catch (final ClassNotFoundException ignore) {
		}
		// Try to register 1.8 player listeners
		try {
			Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent");
			pm.registerEvents(new AuthMePlayerListener18(this), this);
		} catch (final ClassNotFoundException ignore) {
		}
		pm.registerEvents(new AuthMeBlockListener(this), this);
		pm.registerEvents(new AuthMeEntityListener(this), this);
		pm.registerEvents(new AuthMeServerListener(this), this);

		// Register commands
		getCommand("authme").setExecutor(new AdminCommand(this));
		getCommand("register").setExecutor(new RegisterCommand(this));
		getCommand("login").setExecutor(new LoginCommand(this));
		getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
		getCommand("logout").setExecutor(new LogoutCommand(this));
		getCommand("unregister").setExecutor(new UnregisterCommand(this));
		getCommand("captcha").setExecutor(new CaptchaCommand(this));
		getCommand("converter").setExecutor(new ConverterCommand(this));

		// Purge on start if enabled
		autoPurge();

		// Start Email recall task if needed
		recallEmail();

		// Configuration Security Warnings
		if (!Settings.isForceSingleSessionEnabled) {
			ConsoleLogger.showError("警告!!! 你关闭了单点登录保护 玩家帐号可能被顶下线!");
		}
		if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) {
			ConsoleLogger.showError("警告!!! 你配置了Session超时为0 请注意账户的安全问题!");
		}

		// Successful message
		ConsoleLogger.info("AuthMe 版本 " + this.getDescription().getVersion() + " 已正确载入 重制 By 喵♂呜 !");
		new VersionChecker(this);
	}

	@Override
	public void reloadConfig() {
		config.reload();
	}

	public String replaceAllInfos(String message, final Player player) {
		final int playersOnline = Utils.getOnlinePlayers().size();
		message = message.replace("&", "§");
		message = message.replace("{PLAYER}", player.getName());
		message = message.replace("{ONLINE}", "" + playersOnline);
		message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers());
		message = message.replace("{IP}", getIP(player));
		message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
		message = message.replace("{WORLD}", player.getWorld().getName());
		message = message.replace("{SERVER}", server.getServerName());
		message = message.replace("{VERSION}", server.getBukkitVersion());
		message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player)));
		return message;
	}

	@Override
	public void saveConfig() {
		config.save();
	}

	@Override
	public void saveDefaultConfig() {
		config = new FileConfig(this);
	}

	// Save Player Data
	public void savePlayer(final Player player) {
		if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) {
			return;
		}
		final String name = player.getName().toLowerCase();
		if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
			final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player
					.getWorld()
					.getName(), player.getName());
			database.updateQuitLoc(auth);
		}
		if (LimboCache.getInstance().hasLimboPlayer(name)) {
			final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
			if (!Settings.noTeleport) {
				player.teleport(limbo.getLoc());
			}

			Utils.addNormal(player, limbo.getGroup());
			player.setOp(limbo.getOperator());
			limbo.getTimeoutTaskId().cancel();
			LimboCache.getInstance().deleteLimboPlayer(name);
			if (this.playerBackup.doesCacheExist(player)) {
				this.playerBackup.removeCache(player);
			}
		}
		PlayerCache.getInstance().removePlayer(name);
		database.setUnlogged(name);
		player.saveData();
	}

	public void setMessages(final Messages m) {
		this.m = m;
	}

	// Initialize and setup the database
	public void setupDatabase() throws Exception {
		if (database != null) {
			database.close();
		}
		// Backend MYSQL - FILE - SQLITE - SQLITEHIKARI
		boolean isSQLite = false;
		switch (Settings.getDataSource) {
		case FILE:
			database = new FlatFile();
			break;
		case MYSQL:
			database = new MySQL();
			break;
		case SQLITE:
			database = new SQLite();
			isSQLite = true;
			break;
		case SQLITEHIKARI:
			database = new SQLite_HIKARI();
			isSQLite = true;
			break;
		}
		if (isSQLite) {
			server.getScheduler().runTaskAsynchronously(this, new Runnable() {
				@Override
				public void run() {
					final int accounts = database.getAccountsRegistered();
					if (accounts >= 4000) {
						ConsoleLogger.showError("您使用 SQLite 存储了超过 " + accounts + " 个账户, 为了获得更好的性能, 建议使用MySQL!!!");
					}
				}
			});
		}
		if (Settings.isCachingEnabled) {
			database = new CacheDataSource(this, database);
		} else {
			database = new DatabaseCalls(database);
		}

		if (Settings.getDataSource == DataSource.DataSourceType.FILE) {
			final Converter converter = new ForceFlatToSqlite(database, this);
			server.getScheduler().runTaskAsynchronously(this, converter);
			ConsoleLogger.info("+================================================");
			ConsoleLogger.info("| 数据格式 FlatFile 已经过时并且被弃用...");
			ConsoleLogger.info("| 下一次启动服务器, 数据格式将被转换为 SQLite...");
			ConsoleLogger.info("| 转换过程将会在后台异步进行...");
			ConsoleLogger.info("| 这不会影响您的服务器性能...");
			ConsoleLogger.info("| 如果你想继续使用 FlatFile 格式 请修改配置文件...");
			ConsoleLogger.info("| 但是下次重启 插件仍然会进行此操作...");
			ConsoleLogger.info("+================================================");
		}
	}

	// Stop/unload the server/plugin as defined in the configuration
	public void stopOrUnload() {
		if (Settings.isStopEnabled) {
			ConsoleLogger.showError("插件载入发生错误 根据您的配置 服务器即将关闭...");
			server.shutdown();
		} else {
			server.getPluginManager().disablePlugin(AuthMe.getInstance());
		}
		try {
			Thread.sleep(3000);
		} catch (final InterruptedException e1) {
		}
	}

	// Show the exception message and stop/unload the server/plugin as defined
	// in the configuration
	public void stopOrUnload(final Exception e) {
		ConsoleLogger.showError(e.getMessage());
		stopOrUnload();
	}

	public void switchAntiBotMod(final boolean mode) {
		this.antibotMod = mode;
		Settings.switchAntiBotMod(mode);
	}

	// Purge inactive players from the database, as defined in the configuration
	private void autoPurge() {
		if (!Settings.usePurge) {
			return;
		}
		final Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -(Settings.purgeDelay));
		final long until = calendar.getTimeInMillis();
		final List<String> cleared = database.autoPurgeDatabase(until);
		if (cleared == null) {
			return;
		}
		if (cleared.isEmpty()) {
			return;
		}
		ConsoleLogger.info("自动清理数据库: 移除 " + cleared.size() + " 个 AuthMe 账户");
		if (Settings.purgeEssentialsFile && this.ess != null) {
			dataManager.purgeEssentials(cleared); // name to UUID convertion
		}
		// needed with latest versions
		if (Settings.purgePlayerDat) {
			dataManager.purgeDat(cleared); // name to UUID convertion needed
		}
		// with latest versions of MC
		if (Settings.purgeLimitedCreative) {
			dataManager.purgeLimitedCreative(cleared);
		}
		if (Settings.purgeAntiXray) {
			dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or
		}
		// names... (Actually it purges only names!)
		if (Settings.purgePermissions) {
			dataManager.purgePermissions(cleared, permission);
		}
	}

	// Return the authme soawnpoint
	private Location getAuthMeSpawn(final Player player) {
		if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) {
			return Spawn.getInstance().getFirstSpawn();
		}
		if (Spawn.getInstance().getSpawn() != null) {
			return Spawn.getInstance().getSpawn();
		}
		return player.getWorld().getSpawnLocation();
	}

	// Return the default spawnpoint of a world
	private Location getDefaultSpawn(final World world) {
		return world.getSpawnLocation();
	}

	// Return the essentials spawnpoint
	private Location getEssentialsSpawn() {
		if (essentialsSpawn != null) {
			return essentialsSpawn;
		}
		return null;
	}

	private void recallEmail() {
		if (!Settings.recallEmail) {
			return;
		}
		Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {

			@Override
			public void run() {
				for (final Player player : Utils.getOnlinePlayers()) {
					if (player.isOnline()) {
						final String name = player.getName().toLowerCase();
						if (database.isAuthAvailable(name)) {
							if (PlayerCache.getInstance().isAuthenticated(name)) {
								final String email = database.getAuth(name).getEmail();
								if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) {
									m.send(player, "add_email");
								}
							}
						}
					}
				}
			}
		}, 1, 1200 * Settings.delayRecall);
	}

	// Set the console filter to remove the passwords
	private void setLog4JFilter() {
		Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {

			@Override
			public void run() {
				final org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
				coreLogger.addFilter(new Log4JFilter());
			}
		});
	}
}
