package vg.civcraft.mc.civmodcore.scoreboard.bottom;

import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.BiFunction;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import vg.civcraft.mc.civmodcore.CivModCorePlugin;

public class BottomLine implements Comparable<BottomLine>{
	
	private Map <UUID, String> texts;
	private String identifier;
	private BukkitRunnable updater;
	private int priority;
	
	BottomLine(String identifier, int priority) {
		this.identifier = identifier;
		this.priority = priority;
		this.texts = new TreeMap<>();
	}
	
	public String getIdentifier() {
		return identifier;
	}
	
	public void updatePlayer(Player player, String text) {
		texts.put(player.getUniqueId(), text);
	}
	
	public String getCurrentText(UUID uuid) {
		return texts.get(uuid);
	}
	
	public void updatePeriodically(BiFunction<Player, String, String> updateFunction, long delay) {
		if (updater != null) {
			updater.cancel();
		}
		updater = new BukkitRunnable() {

			@Override
			public void run() {
				for (Entry<UUID, String> entry : texts.entrySet()) {
					Player player = Bukkit.getPlayer(entry.getKey());
					if (player != null) {
						String newText = updateFunction.apply(player, entry.getValue());
						if (!newText.equals(entry.getValue()) ) {
							entry.setValue(newText);
							BottomLineAPI.refreshIndividually(player.getUniqueId());
						}
						
					}
				}
			}
		};
		updater.runTaskTimer(CivModCorePlugin.getInstance(), delay, delay);
	}
	
	public void removePlayer(Player player) {
		texts.remove(player.getUniqueId());
		BottomLineAPI.refreshIndividually(player.getUniqueId());
	}
	
	Map<UUID, String> getAll() {
		return texts;
	}
	
	@Override
	public boolean equals(Object o) {
		return o == this;
	}

	@Override
	public int compareTo(BottomLine o) {
		int prio = Integer.compare(priority, o.priority);
		if (prio != 0) {
			return prio;
		}
		return Integer.compare(hashCode(), o.hashCode());
	}

}

@@ -47,16 +47,43 @@
 ottom;%0A%0A
+import java.util.Iterator;%0A
 import j
@@ -1156,13 +1156,17 @@
 %09%09%09%09
-for (
+Iterator%3C
 Entr
@@ -1184,16 +1184,17 @@
 ing%3E
- entry :
+%3E  iter =
  tex
@@ -1206,19 +1206,104 @@
 trySet()
-) %7B
+.iterator();%0A%09%09%09%09while (iter.hasNext()) %7B%0A%09%09%09%09%09Entry %3CUUID, String%3E entry = iter.next();
 %0A%09%09%09%09%09Pl
@@ -1444,24 +1444,100 @@
 etValue());%0A
+%09%09%09%09%09%09if (newText == null) %7B%0A%09%09%09%09%09%09%09iter.remove();%0A%09%09%09%09%09%09%09continue;%0A%09%09%09%09%09%09%7D%0A
 %09%09%09%09%09%09if (!n
@@ -1668,24 +1668,24 @@
 eId());%0A
+
 %09%09%09%09%09%09%7D%0A
 %09%09%09%09%09%09%0A%09
@@ -1680,15 +1680,8 @@
 %09%09%7D%0A
-%09%09%09%09%09%09%0A
 %09%09%09%09

Allow removal from periodic updattes in BottomLineAPI