package me.loganb1max.minionsplus.manager;

import me.loganb1max.minionsplus.MinionsPlus;
import me.loganb1max.minionsplus.model.Minion;
import me.loganb1max.minionsplus.util.Text;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
import java.util.Map;

public class LinkingManager implements Listener {

	private final MinionsPlus plugin;
	private final BukkitTask timerTask;
	private Map<Player, Minion> linkingMap = new HashMap<>();
	private Map<Player, Integer> timeMap = new HashMap<>();

	public LinkingManager(final MinionsPlus plugin) {
		this.plugin = plugin;
		Bukkit.getPluginManager().registerEvents(this, this.plugin);
		this.timerTask = Bukkit.getScheduler().runTaskTimer(this.plugin, () -> {
			for (Map.Entry<Player, Integer> entry : timeMap.entrySet()) {
				if (entry.getValue() > 0) entry.setValue(entry.getValue() - 1);
				else endLinking(entry.getKey());
			}
		}, 20, 20);
	}

	public void close() {
		HandlerList.unregisterAll(this);
		this.timerTask.cancel();
	}

	public void beginLinking(final Player player, final Minion minion) {
		this.linkingMap.put(player, minion);
		this.timeMap.put(player, 15);
		player.sendMessage(Text.color("&aYou have begun linking new blocks for " + minion.getName() + ". (15 Seconds)"));
	}

	private void endLinking(final Player player) {
		this.linkingMap.remove(player);
		this.timeMap.remove(player);
		player.sendMessage(Text.color("&cYou are no longer linking blocks."));
	}

	@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
	private void onLink(final PlayerInteractEvent e) {
		if (!this.linkingMap.containsKey(e.getPlayer())) return;
		if (!e.hasBlock()) {
			e.getPlayer().sendMessage(Text.color("&cYou must click on a block."));
			return;
		}
		final Minion minion = this.linkingMap.get(e.getPlayer());
		final Block block = e.getClickedBlock();
		if (minion.getLinkedBlocks().contains(block)) {
			minion.getLinkedBlocks().remove(block);
			e.getPlayer().sendMessage(Text.color("&aSuccessfully unlinked block."));
		} else {
			minion.getLinkedBlocks().add(block);
			e.getPlayer().sendMessage(Text.color("&aSuccessfully linked block."));
		}
		endLinking(e.getPlayer());
		e.setCancelled(true);
	}

}
