package de.hessj.environmentex;

import org.bukkit.Material;
import org.bukkit.block.ShulkerBox;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
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.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.BlockStateMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;

import net.kyori.adventure.text.Component;

public class ShulkerPreview implements Listener{
 @EventHandler
    public void shulkerGuiCloseEvent(InventoryCloseEvent e){
        if(e.getInventory().getHolder() instanceof ShulkerGui){
            ShulkerGui gui = (ShulkerGui) e.getInventory().getHolder();
            gui.update(true);


        }
    }

    @EventHandler
    public void shulkerGuiClickEvent(InventoryClickEvent e){
        Player player = (Player) e.getWhoClicked();
        if(e.getView().getTopInventory().getHolder() instanceof ShulkerGui){
            ShulkerGui gui = (ShulkerGui) e.getView().getTopInventory().getHolder();
            gui.update(false);

            if((e.getClick() == ClickType.NUMBER_KEY && gui.getSlot() == e.getHotbarButton()) || (e.getCurrentItem() != null && e.getCurrentItem().getType().name().endsWith("SHULKER_BOX"))){
                e.setCancelled(true);
            }
        }
        if(e.getCurrentItem() != null && e.getClickedInventory() instanceof PlayerInventory && e.getClick().toString().equals("SHIFT_RIGHT")){
            if(e.getCurrentItem().getType().toString().endsWith("_BOX")){
                e.setCancelled(true);
                ItemStack item = e.getCurrentItem().clone();
                BlockStateMeta im = (BlockStateMeta) item.getItemMeta();
                ShulkerBox shulker = (ShulkerBox) im.getBlockState();
                Component displayName = Component.text("Shulker-Kiste");
                if(item.getItemMeta() != null){
                    ItemMeta meta = item.getItemMeta();
                    if(meta.hasDisplayName()){
                        displayName = item.getItemMeta().displayName();
                    }
                }
                ShulkerGui gui = new ShulkerGui(player, shulker,e.getSlot(),item,displayName);
                gui.open();
            }
            else if(e.getCurrentItem().getType()==Material.ENDER_CHEST){
                e.setCancelled(true);
                new BukkitRunnable(){
                    @Override
                    public void run() {
                        player.openInventory(player.getEnderChest());   
                    }
                }.runTaskLater(App.main, 1);
            }
        }
    }
}
