package com.nicewuerfel.blockown.protection;
import com.nicewuerfel.blockown.Setting;
import com.nicewuerfel.blockown.Setting.PROTECTION;
import com.nicewuerfel.blockown.User;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
public class ProtectionDecayer implements Runnable {
private final Setting setting;
private final Protection protection;
private final Plugin plugin;
/**
* Maps the UUID string of players to the last time they've been dropped.
*/
private final Map<String, Long> checked;
private BukkitTask schedulerTask = null;
ProtectionDecayer(@Nonnull Setting setting, @Nonnull Protection protection,
@Nonnull Plugin plugin) {
this.protection = protection;
this.plugin = plugin;
this.setting = setting;
this.checked = new HashMap<>(plugin.getServer().getOfflinePlayers().length * 2);
}
/**
* Schedules an possibly asynchronous cleanup after {@link PROTECTION#DECAY} which repeats every
* 2* {@link PROTECTION#DECAY} hours.<br>
* If {@link PROTECTION#DECAY} is 0, no task will be scheduled.<br>
* Cancels all tasks created by previous calls to this method.
*/
public void start() {
schedule(getSetting().PROTECTION.DECAY * 3600);
}
/**
* Cancels all ProtectionDecayer tasks. If this task is not scheduled, does nothing.
*/
public void stop() {
BukkitScheduler scheduler = plugin.getServer().getScheduler();
if (schedulerTask != null) {
if (scheduler.isQueued(schedulerTask.getTaskId())) {
scheduler.cancelTask(schedulerTask.getTaskId());
}
}
schedulerTask = null;
}
/**
* Schedules this task after the given time in seconds. Doesn't schedule the task if delay is 0.
*
* @param delay the delay in seconds
*/
private void schedule(long delay) {
BukkitScheduler scheduler = plugin.getServer().getScheduler();
stop();
delay *= 20;
if (delay != 0) {
schedulerTask = scheduler.runTaskLaterAsynchronously(plugin, this, delay);
}
}
@Override
public void run() {
long now = System.currentTimeMillis();
for (OfflinePlayer player : plugin.getServer().getOfflinePlayers()) {
String uuid = player.getUniqueId().toString();
Long checkedTime = checked.get(player.getUniqueId().toString());
if (checkedTime == null) {
checkedTime = Long.valueOf(0);
}
if (player.getLastPlayed() > checkedTime) {
if (now - player.getLastPlayed() > getSetting().PROTECTION.DECAY * 1000 * 3600) {
User user = User.getInstance(player.getUniqueId());
ProtectAction protectAction = new ProtectAction.Builder(user).drop().build();
getProtection().enqueue(protectAction);
checked.put(uuid, now);
}
}
}
schedule(getSetting().PROTECTION.DECAY * 2 * 3600);
}
private Protection getProtection() {
return protection;
}
private Setting getSetting() {
return setting;
}
}