package me.loganb1max.minions.menu;

import me.loganb1max.minions.MinionsPlugin;
import me.loganb1max.minions.model.Minion;
import me.loganb1max.minions.util.ItemBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Material;
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.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class MinionMenu implements Listener {

	private final Minion minion;
	private final Player player;
	private final Inventory inventory;
	private final Map<Integer, Consumer<ClickType>> clickHandlerMap = new HashMap<>();

	public MinionMenu(final Minion minion, final Player player) {
		this.minion = minion;
		this.player = player;
		Bukkit.getPluginManager().registerEvents(this, MinionsPlugin.getInstance());
		this.inventory = Bukkit.createInventory(this.player, 9, "Minion Menu");

		bindItem(
				ItemBuilder.of(Material.CHEST)
				.name("&6Link Chest")
				.lore("&7click to link a deposit chest.")
				.build(),
				2,
				clickType -> {

				}
		);

		bindItem(
				minion.getIcon(),
				4,
				clickType -> { }
		);

		bindItem(
				ItemBuilder.of(Material.GOLD_INGOT)
				.name("&6Upgrade")
				.lore("&7click to upgrade this minion.")
				.build(),
				6,
				clickType -> {

				}
		);

		this.player.openInventory(this.inventory);
	}

	private void bindItem(final ItemStack item, final int slot, final Consumer<ClickType> consumer) {
		this.inventory.setItem(slot, item);
		this.clickHandlerMap.remove(slot);
		this.clickHandlerMap.put(slot, consumer);
		this.player.updateInventory();
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onClose(final InventoryCloseEvent e) {
		if (!e.getInventory().equals(this.inventory)) return;
		HandlerList.unregisterAll(this);
	}

	@EventHandler(priority = EventPriority.HIGHEST)
	public void onClick(final InventoryClickEvent e) {
		if (!e.getClickedInventory().equals(this.inventory)) return;
		e.setCancelled(true);
		this.clickHandlerMap.get(e.getSlot()).accept(e.getClick());
	}

}
