package cn.citycraft.AuthMe.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import cn.citycraft.AuthMe.AuthMe;
import cn.citycraft.AuthMe.cache.auth.PlayerCache;
import cn.citycraft.AuthMe.settings.Messages;
import cn.citycraft.AuthMe.settings.Settings;
import cn.citycraft.AuthMe.task.ChangePasswordTask;

public class ChangePasswordCommand implements CommandExecutor {

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

	public ChangePasswordCommand(AuthMe plugin) {
		this.plugin = plugin;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
		if (!(sender instanceof Player)) {
			return true;
		}

		if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
			m.send(sender, "no_perm");
			return true;
		}

		Player player = (Player) sender;
		String name = player.getName().toLowerCase();
		if (!PlayerCache.getInstance().isAuthenticated(name)) {
			m.send(player, "not_logged_in");
			return true;
		}

		if (args.length != 2) {
			m.send(player, "usage_changepassword");
			return true;
		}

		String lowpass = args[1].toLowerCase();
		if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select")
				|| lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
			m.send(player, "password_error");
			return true;
		}
		if (lowpass.equalsIgnoreCase(name)) {
			m.send(player, "password_error_nick");
			return true;
		}
		if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
			m.send(player, "pass_len");
			return true;
		}
		if (!Settings.unsafePasswords.isEmpty()) {
			if (Settings.unsafePasswords.contains(lowpass)) {
				m.send(player, "password_error_unsafe");
				return true;
			}
		}
		plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0], args[1]));
		return true;
	}
}
