package cn.citycraft.AuthMe.process.register;

import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;

import cn.citycraft.AuthMe.AuthMe;
import cn.citycraft.AuthMe.ConsoleLogger;
import cn.citycraft.AuthMe.Utils;
import cn.citycraft.AuthMe.cache.limbo.LimboCache;
import cn.citycraft.AuthMe.cache.limbo.LimboPlayer;
import cn.citycraft.AuthMe.settings.Messages;
import cn.citycraft.AuthMe.settings.Settings;
import cn.citycraft.AuthMe.task.MessageTask;
import cn.citycraft.AuthMe.task.TimeoutTask;

public class ProcessSyncronousEmailRegister implements Runnable {

	private Messages m = Messages.getInstance();
	private AuthMe plugin;
	protected String name;
	protected Player player;

	public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) {
		this.player = player;
		this.name = player.getName().toLowerCase();
		this.plugin = plugin;
	}

	@Override
	public void run() {
		LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
		if (!Settings.getRegisteredGroup.isEmpty()) {
			Utils.setGroup(player, Utils.GroupType.REGISTERED);
		}
		m.send(player, "vb_nonActiv");
		int time = Settings.getRegistrationTimeout * 20;
		int msgInterval = Settings.getWarnMessageInterval;

		BukkitScheduler sched = plugin.getServer().getScheduler();
		if (time != 0 && limbo != null) {
			limbo.getTimeoutTaskId().cancel();
			BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time);
			limbo.setTimeoutTaskId(id);
		}
		if (limbo != null) {
			limbo.getMessageTaskId().cancel();
			BukkitTask nwMsg = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), msgInterval));
			limbo.setMessageTaskId(nwMsg);
		}

		player.saveData();
		if (!Settings.noConsoleSpam)
			ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player));
	}

}
