Newer
Older
ChallengesJoinEntities / src / main / java / de / fanta / challengesjoinentities / utils / ui / WindowManager.java
@fanta fanta on 29 Nov 2021 2 KB Update to 1.18-rc3
package de.fanta.challengesjoinentities.utils.ui;

import de.fanta.challenges.Challenges;
import de.fanta.challengesjoinentities.ChallengesJoinEntities;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.plugin.Plugin;

public class WindowManager implements Listener {
  private static final WindowManager INSTANCE = new WindowManager();

  private final ChallengesJoinEntities plugin = ChallengesJoinEntities.getPlugin();
  
  private Map<UUID, Window> openWindows;
  
  public WindowManager() {
    this.openWindows = new HashMap<>();
    Bukkit.getPluginManager().registerEvents(this, plugin);
  }
  
  public void registerOpenWindow(Window window) {
    Window alreadyOpen = this.openWindows.put(window.getPlayer().getUniqueId(), window);
    if (alreadyOpen != null)
      plugin.getLogger().log(Level.WARNING, "Window opened without the last one being closed.");
  }
  
  @EventHandler
  public void onInventoryClickEvent(InventoryClickEvent event) {
    Window window = this.openWindows.get(event.getWhoClicked().getUniqueId());
    if (window == null)
      return; 
    try {
      window.onItemClicked(event);
    } catch (Exception e) {
      event.setCancelled(true);
      throw e;
    } 
  }
  
  @EventHandler
  public void onInventoryDragEvent(InventoryDragEvent event) {
    Window window = this.openWindows.get(event.getWhoClicked().getUniqueId());
    if (window == null)
      return; 
    try {
      window.onItemDraged(event);
    } catch (Exception e) {
      event.setCancelled(true);
      throw e;
    } 
  }
  
  @EventHandler
  public void onInventoryClosedEvent(InventoryCloseEvent event) {
    Window window = this.openWindows.get(event.getPlayer().getUniqueId());
    if (window == null)
      return; 
    window.closed(event);
    this.openWindows.remove(event.getPlayer().getUniqueId());
  }
  
  public static WindowManager getInstance() {
    return INSTANCE;
  }
}