package de.hessj.environmentex;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.Sound;
import org.bukkit.SoundCategory;
import org.bukkit.Statistic;
import org.bukkit.Tag;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.Ageable;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Fence;
import org.bukkit.block.data.type.Leaves;
import org.bukkit.block.data.type.Stairs;
import org.bukkit.entity.Axolotl;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fish;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.entity.Squid;
import org.bukkit.entity.WanderingTrader;
import org.bukkit.entity.memory.MemoryKey;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.Event.Result;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityTargetLivingEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.event.player.PlayerAttemptPickupItemEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.util.Vector;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import net.kyori.adventure.text.Component;
import de.hessj.helper.Helper;
import de.hessj.helper.Helper.*;

public class EnvironmentExListeners implements Listener {
    public static boolean voteIsGoing = false;
    public static int voteForYes;
    public static int voteForNo;
    public static int onlinePlayers;
    public static ArrayList<UUID> hasVoted = new ArrayList<UUID>();
    public static Location lastLoc;

    public de.hessj.helper.Helper helper = new de.hessj.helper.Helper();

    boolean isAlone() {
        int online = App.main.getServer().getOnlinePlayers().size();
        if (online <= 1) {
            return true;
        }
        return false;
    }

    @EventHandler
    public void onBedEnter(PlayerBedEnterEvent e) {

        e.getPlayer().setStatistic(Statistic.TIME_SINCE_REST, 0);

        switch (e.getBedEnterResult()) {
            case OK:

                e.setCancelled(true);
                e.setUseBed(Result.ALLOW);
                if (!voteIsGoing) {
                    if (isAlone()) {
                        if (e.getBed().getWorld().isThundering()) {
                            e.getPlayer()
                                    .sendMessage(helper.R3SMessage(Type.SUCCESS, "Das Gewitter wird durchgeschlafen."));
                            Bukkit.getWorlds().get(0).setTime(24000);
                            Bukkit.getWorlds().get(0).setStorm(false);
                            Bukkit.getWorlds().get(0).setThundering(false);
                            Bukkit.getWorlds().get(0).setWeatherDuration(6000);

                        } else {

                            e.getPlayer()
                                    .sendMessage(helper.R3SMessage(Type.SUCCESS, "Die Nacht wird durchgeschlafen."));
                            Bukkit.getWorlds().get(0).setTime(24000);
                        }

                        return;
                    }

                    voteIsGoing = true;
                    voteForYes = 1;
                    voteForNo = 0;
                    onlinePlayers = 0;
                    hasVoted.add(e.getPlayer().getUniqueId());
                    for (Player p : App.main.getServer().getOnlinePlayers()) {
                        onlinePlayers++;
                        if (e.getBed().getWorld().isThundering()) {

                            p.sendMessage(helper.R3SMessage(Type.INFO, e.getPlayer().getName()
                                    + " möchte das Gewitter überspringen. Stimme mit /y für Ja oder mit /n für Nein ab."));

                        } else {
                            p.sendMessage(helper.R3SMessage(Type.INFO, e.getPlayer().getName()
                                    + " möchte die Nacht überspringen. Stimme mit /y für Ja oder mit /n für Nein ab."));

                        }

                        p.sendMessage(helper.R3SMessage(Type.INFO, "Du hast ab jetzt 10 Sekunden Zeit."));

                    }
                    Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                        public void run() {
                            voteIsGoing = false;
                            hasVoted = new ArrayList<UUID>();
                            if (voteForYes > voteForNo) {

                                for (Player p : App.main.getServer().getOnlinePlayers()) {
                                    if (e.getBed().getWorld().isThundering()) {

                                        p.sendMessage(helper.R3SMessage(Type.OK, "Das Gewitter wird durchgeschlafen. ("
                                                + voteForYes + "x Ja, " + voteForNo + "x Nein, "
                                                + (onlinePlayers - voteForNo - voteForYes) + "x enthalten)"));

                                    }

                                    else {

                                        p.sendMessage(helper.R3SMessage(Type.OK, "Die Nacht wird durchgeschlafen. ("
                                                + voteForYes + "x Ja, " + voteForNo + "x Nein, "
                                                + (onlinePlayers - voteForNo - voteForYes) + "x enthalten)"));

                                    }
                                }

                                if (e.getBed().getWorld().isThundering()) {
                                    Bukkit.getWorlds().get(0).setTime(24000);
                                    Bukkit.getWorlds().get(0).setStorm(false);
                                    Bukkit.getWorlds().get(0).setThundering(false);
                                    Bukkit.getWorlds().get(0).setWeatherDuration(6000);
                                } else {
                                    Bukkit.getWorlds().get(0).setTime(24000);
                                }

                            } else if (voteForNo >= voteForYes) {

                                for (Player p : App.main.getServer().getOnlinePlayers()) {
                                    if (e.getBed().getWorld().isThundering()) {

                                        p.sendMessage(helper.R3SMessage(Type.ERROR,
                                                "Das Gewitter wird nicht durchgeschlafen. (" + voteForYes + "x Ja, "
                                                        + voteForNo
                                                        + "x Nein, " + (onlinePlayers - voteForNo - voteForYes)
                                                        + "x enthalten)"));

                                    } else {
                                        p.sendMessage(helper.R3SMessage(Type.ERROR,
                                                "Die Nacht wird nicht durchgeschlafen. (" + voteForYes + "x Ja, "
                                                        + voteForNo
                                                        + "x Nein, " + (onlinePlayers - voteForNo - voteForYes)
                                                        + "x enthalten)"));
                                    }
                                    if (p.isSleeping()) {
                                        p.wakeup(true);
                                    }
                                }
                            }
                        }

                    }, 20 * 10);
                } else if (voteIsGoing) {
                    if (!hasVoted.contains(e.getPlayer().getUniqueId())) {
                        voteForYes++;
                        hasVoted.add(e.getPlayer().getUniqueId());
                        e.getPlayer().sendMessage(helper.R3SMessage(Type.INFO, "Du hast für Ja gevotet."));
                    }
                }
                break;
            case NOT_POSSIBLE_NOW:
                e.setCancelled(true);
                e.getPlayer().sendMessage(
                        helper.R3SMessage(Type.ERROR, "Du kannst nur nachts oder während eines Gewitters schlafen"));
                break;
            case NOT_SAFE:
                e.setCancelled(true);
                e.getPlayer().sendMessage(
                        helper.R3SMessage(Type.ERROR, "Du kannst jetzt nicht schlafen, es sind Monster in der Nähe"));
                break;
            case TOO_FAR_AWAY:
                e.setCancelled(true);
                e.getPlayer().sendMessage(
                        helper.R3SMessage(Type.ERROR, "Du kannst jetzt nicht schlafen, das Bett ist zu weit entfernt"));
                break;
            case OBSTRUCTED:
                e.setCancelled(true);
                e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR, "Dieses Bett ist blockiert"));
                break;

            default:
                App.main.hmActionbar.put(e.getPlayer(), false);
                Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                    public void run() {
                        App.main.hmActionbar.put(e.getPlayer(), true);
                    }
                }, 20 * 3);
                break;
        }

    }

    @EventHandler
    public void soilChangePlayer(PlayerInteractEvent event) {
        if (event.getAction() == Action.PHYSICAL && event.getClickedBlock().getType() == Material.FARMLAND) {
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void soilChangeEntity(EntityInteractEvent event) {
        if (event.getEntityType() != EntityType.PLAYER && event.getBlock().getType() == Material.FARMLAND) {
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onClick(PlayerInteractEvent e) {
        if (e.getAction() == Action.LEFT_CLICK_BLOCK
                && (e.getClickedBlock().getType() == Material.WHEAT || e.getClickedBlock().getType() == Material.CARROTS
                        || e.getClickedBlock().getType() == Material.ATTACHED_MELON_STEM
                        || e.getClickedBlock().getType() == Material.MELON_STEM
                        || e.getClickedBlock().getType() == Material.ATTACHED_PUMPKIN_STEM
                        || e.getClickedBlock().getType() == Material.PUMPKIN_STEM
                        || e.getClickedBlock().getType() == Material.POTATOES
                        || e.getClickedBlock().getType() == Material.BEETROOTS)) {
            if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.WOODEN_HOE)) {
                harvest(0, e);
            } else if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.STONE_HOE)) {
                harvest(0, e);
            } else if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.IRON_HOE)) {
                harvest(1, e);
            } else if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.GOLDEN_HOE)) {
                harvest(2, e);
            } else if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.DIAMOND_HOE)) {
                harvest(3, e);
            } else if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.NETHERITE_HOE)) {
                harvest(4, e);
            }
        }
    }

    public static int harvestDMG(Material weapon) {

        double perc = 0.70;

        if (weapon == Material.WOODEN_HOE) {
            perc = 0.70;
        } else if (weapon == Material.STONE_HOE) {
            perc = 0.75;
        } else if (weapon == Material.IRON_HOE) {
            perc = 0.80;
        } else if (weapon == Material.GOLDEN_HOE) {
            perc = 0.85;
        } else if (weapon == Material.DIAMOND_HOE) {
            perc = 0.90;
        } else if (weapon == Material.NETHERITE_HOE) {
            perc = 0.95;
        }      

        Random rand = new Random();
        return (rand.nextDouble() < perc) ? 0 : 1;
    }

    void harvest(int radius, PlayerInteractEvent e) {
        e.setCancelled(true);
        Block middle = e.getClickedBlock();
        Material cropM = middle.getType();

        ItemStack isCropM;
        switch (cropM) {
            case POTATOES:
                isCropM = new ItemStack(Material.POTATO, 1);
                break;
            case BEETROOTS:
                isCropM = new ItemStack(Material.BEETROOT, 1);
                break;
            case WHEAT:
                isCropM = new ItemStack(Material.WHEAT, 1);
                break;
            case CARROTS:
                isCropM = new ItemStack(Material.CARROT, 1);
                break;
            default:
                isCropM = new ItemStack(Material.AIR, 0);
                break;

        }
        if (middle.getBlockData() instanceof Ageable) {
            Ageable ab = (Ageable) middle.getBlockData();
            if (ab.getAge() == ab.getMaximumAge()) {
                if (e.getPlayer().getInventory().getItemInMainHand() != null
                        && ((Damageable) e.getPlayer().getInventory().getItemInMainHand().getItemMeta())
                                .getDamage() <= e
                                        .getPlayer().getInventory().getItemInMainHand().getType().getMaxDurability()) {
                    if (cropM != Material.PUMPKIN_STEM && cropM != Material.MELON_STEM) {
                        middle.setType(Material.AIR);
                        Bukkit.getWorlds().get(0).dropItem(middle.getLocation(), isCropM);

                        ItemStack is = e.getPlayer().getInventory().getItemInMainHand();
                        ItemMeta meta = is.getItemMeta();
                        Damageable d = (Damageable) meta;
                        d.setDamage(d.getDamage() + harvestDMG(is.getType()));
                        is.setItemMeta(meta);
                        middle.setType(cropM);
                    }
                }
                if (e.getPlayer().getInventory().getItemInMainHand() != null
                        && ((Damageable) e.getPlayer().getInventory().getItemInMainHand().getItemMeta())
                                .getDamage() >= e
                                        .getPlayer().getInventory().getItemInMainHand().getType().getMaxDurability()) {
                    e.getPlayer().getInventory().clear(e.getPlayer().getInventory().getHeldItemSlot());
                    e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, 1, 1);
                }
            }
        }
        if (radius != 0) {
            Vector direction = e.getPlayer().getLocation().getDirection();
            Location location = e.getPlayer().getEyeLocation();
            location.add(direction.multiply(1.5D));
            e.getPlayer().getWorld().spawnParticle(Particle.SWEEP_ATTACK, location, 1);

            for (int x = radius; x >= -radius; x--) {
                for (int y = radius; y >= -radius; y--) {
                    for (int z = radius; z >= -radius; z--) {
                        BlockData bd = (BlockData) middle.getRelative(x, y, z).getBlockData();
                        if (bd instanceof Ageable) {
                            Ageable abR = (Ageable) bd;
                            if (abR.getAge() == abR.getMaximumAge()) {
                                try {
                                    if (e.getPlayer().getInventory().getItemInMainHand() != null
                                            && ((Damageable) e.getPlayer().getInventory().getItemInMainHand()
                                                    .getItemMeta()).getDamage() <= e.getPlayer().getInventory()
                                                            .getItemInMainHand().getType().getMaxDurability()) {
                                        Material crop = middle.getRelative(x, y, z).getType();

                                        Location loc = middle.getRelative(x, y, z).getLocation();

                                        ItemStack isCrop;

                                        switch (crop) {
                                            case POTATOES:
                                                isCrop = new ItemStack(Material.POTATO, 1);
                                                break;
                                            case BEETROOTS:
                                                isCrop = new ItemStack(Material.BEETROOT, 1);
                                                break;
                                            case WHEAT:
                                                isCrop = new ItemStack(Material.WHEAT, 1);
                                                break;
                                            case CARROTS:
                                                isCrop = new ItemStack(Material.CARROT, 1);
                                                break;
                                            default:
                                                isCrop = new ItemStack(Material.AIR, 0);
                                                break;

                                        }

                                        // middle.getRelative(x, y, z).breakNaturally(new ItemStack(Material.AIR));
                                        if (crop != Material.PUMPKIN_STEM && crop != Material.MELON_STEM) {
                                            middle.getRelative(x, y, z).setType(Material.AIR);
                                            Bukkit.getWorlds().get(0).dropItem(loc, isCrop);

                                            middle.getRelative(x, y, z).setType(crop);

                                            ItemStack is = e.getPlayer().getInventory().getItemInMainHand();
                                            ItemMeta meta = is.getItemMeta();
                                            Damageable d = (Damageable) meta;
                                            d.setDamage(d.getDamage() + harvestDMG(is.getType()));
                                            is.setItemMeta(meta);
                                        }
                                    }
                                    if (e.getPlayer().getInventory().getItemInMainHand() != null
                                            && ((Damageable) e.getPlayer().getInventory().getItemInMainHand()
                                                    .getItemMeta()).getDamage() >= e.getPlayer().getInventory()
                                                            .getItemInMainHand().getType().getMaxDurability()) {
                                        e.getPlayer().getInventory()
                                                .clear(e.getPlayer().getInventory().getHeldItemSlot());
                                        e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.ENTITY_ITEM_BREAK, 1,
                                                1);
                                    }
                                } catch (NullPointerException ex) {

                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private long breakDelay = 5;
    private long decayDelay = 2;
    private boolean spawnParticles = true;
    private boolean playSound = true;
    private boolean oneByOne = true;
    private final List<Block> scheduledBlocks = new ArrayList<Block>();
    private static final List<BlockFace> NEIGHBORS;

    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        this.onBlockRemove(event.getBlock(), this.breakDelay);
    }

    @EventHandler
    public void onLeavesDecay(LeavesDecayEvent event) {
        this.onBlockRemove(event.getBlock(), this.decayDelay);
    }

    private void onBlockRemove(Block oldBlock, long delay) {
        if (Tag.LOGS.isTagged(oldBlock.getType()) || Tag.LEAVES.isTagged(oldBlock.getType())) {
            Collections.shuffle(NEIGHBORS);
            Iterator<BlockFace> var5 = NEIGHBORS.iterator();

            while (var5.hasNext()) {
                BlockFace neighborFace = (BlockFace) var5.next();
                Block block = oldBlock.getRelative(neighborFace);
                if (Tag.LEAVES.isTagged(block.getType())) {
                    Leaves leaves = (Leaves) block.getBlockData();
                    if (!leaves.isPersistent() && !this.scheduledBlocks.contains(block)) {
                        if (this.oneByOne) {
                            if (this.scheduledBlocks.isEmpty()) {
                                App.main.getServer().getScheduler().runTaskLater(App.main, this::decayOne, delay);
                            }
                            this.scheduledBlocks.add(block);
                        } else {
                            App.main.getServer().getScheduler().runTaskLater(App.main, () -> {
                                this.decay(block);
                            }, delay);
                        }
                        this.scheduledBlocks.add(block);
                    }
                }
            }
        }
    }

    private boolean decay(Block block) {
        if (!this.scheduledBlocks.remove(block)) {
            return false;
        } else if (!block.getWorld().isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) {
            return false;
        } else if (!Tag.LEAVES.isTagged(block.getType())) {
            return false;
        } else {
            Leaves leaves = (Leaves) block.getBlockData();
            if (leaves.isPersistent()) {
                return false;
            } else if (leaves.getDistance() < 7) {
                return false;
            } else {
                LeavesDecayEvent event = new LeavesDecayEvent(block);
                App.main.getServer().getPluginManager().callEvent(event);
                if (event.isCancelled()) {
                    return false;
                } else {
                    if (this.spawnParticles) {
                        // block.getWorld().spawnParticle(Particle.ASH, block.getLocation().add(0.5D,
                        // 0.5D, 0.5D), 8, 0.2D,
                        // 0.2D, 0.2D, 0.0D, block.getType().createBlockData());
                    }

                    if (this.playSound) {
                        block.getWorld().playSound(block.getLocation(), Sound.BLOCK_GRASS_BREAK, SoundCategory.BLOCKS,
                                0.05F, 1.2F);
                    }

                    block.breakNaturally();
                    return true;
                }
            }
        }
    }

    private void decayOne() {
        boolean decayed = false;

        while (!this.scheduledBlocks.isEmpty()) {
            Block block = (Block) this.scheduledBlocks.get(0);
            decayed = this.decay(block);
            if (decayed) {
                if (!this.scheduledBlocks.isEmpty()) {
                    long delay = this.decayDelay;
                    if (delay <= 0L) {
                        delay = 1L;
                    }
                    App.main.getServer().getScheduler().runTaskLater(App.main, this::decayOne, delay);
                }
                return;
            }
        }

    }

    static {
        NEIGHBORS = Arrays.asList(BlockFace.UP, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST,
                BlockFace.DOWN);
    }

    public static HashMap<Player, Inventory> hm = new HashMap<Player, Inventory>();
    public static HashMap<Player, Inventory> hm2 = new HashMap<Player, Inventory>();
    public static HashMap<Player, Inventory> hm3 = new HashMap<Player, Inventory>();
    public static HashMap<Player, Inventory> hm4 = new HashMap<Player, Inventory>();

    @EventHandler
    public void onItemCollect(PlayerAttemptPickupItemEvent e) throws IOException {

        if (e.getPlayer().getInventory().firstEmpty() == -1 && e.getRemaining() > 0) {
            Item itm = e.getItem();

            if (itm.getItemStack().getType() == Material.BARRIER && e.getItem().getItemStack().hasItemMeta()) {

                if (itm.getItemStack().getItemMeta().getPersistentDataContainer().has(App.main.nsk,
                        PersistentDataType.STRING)
                        && (itm.getItemStack().getItemMeta().getPersistentDataContainer()
                                .get(App.main.nsk, PersistentDataType.STRING).equals("R3S_kleiner_Rucksack"))
                        || (itm.getItemStack().getItemMeta().getPersistentDataContainer().has(App.main.nsk2,
                                PersistentDataType.STRING)
                                && itm.getItemStack().getItemMeta().getPersistentDataContainer()
                                        .get(App.main.nsk2, PersistentDataType.STRING).equals("R3S_Rucksack"))
                        || (itm.getItemStack().getItemMeta().getPersistentDataContainer().has(App.main.nsk3,
                                PersistentDataType.STRING)
                                && itm.getItemStack().getItemMeta().getPersistentDataContainer()
                                        .get(App.main.nsk3, PersistentDataType.STRING).equals("R3S_großer_Rucksack"))
                        || (itm.getItemStack().getItemMeta().getPersistentDataContainer().has(App.main.nsk4,
                                PersistentDataType.STRING)
                                && itm.getItemStack().getItemMeta().getPersistentDataContainer()
                                        .get(App.main.nsk4, PersistentDataType.STRING)
                                        .equals("R3S_riesiger_Rucksack"))) {

                    e.setCancelled(true);
                    return;

                }
            }

            if (e.getPlayer().getInventory().contains(App.main.backPack)) {
                checkBackpack(1, e.getPlayer(), itm.getItemStack());
            }
            if (e.getPlayer().getInventory().contains(App.main.backPack2)) {
                checkBackpack(2, e.getPlayer(), itm.getItemStack());
            }
            if (e.getPlayer().getInventory().contains(App.main.backPack3)) {
                checkBackpack(3, e.getPlayer(), itm.getItemStack());
            }
            if (e.getPlayer().getInventory().contains(App.main.backPack4)) {
                checkBackpack(4, e.getPlayer(), itm.getItemStack());
            }
        }

    }

    public void checkBackpack(int size, Player p, ItemStack i) throws IOException {

        Boolean freespace = false;
        Inventory inv = Bukkit.createInventory(null, 9, Component.translatable("new"));

        if (size == 1) {
            inv = Bukkit.createInventory(null, 9, Component.translatable("tempBackpack"));
            ItemStack[] is;
            is = Helper.itemStackArrayFromBase64(
                    App.main.getConfig().getString(p.getUniqueId() + ".backpack.contents.leatherbackpack"));
            inv.setContents(is);
        } else if (size == 2) {
            inv = Bukkit.createInventory(null, 18, Component.translatable("tempBackpack2"));
            ItemStack[] is;
            is = Helper.itemStackArrayFromBase64(
                    App.main.getConfig().getString(p.getUniqueId() + ".backpack.contents.ironbackpack"));
            inv.setContents(is);
        } else if (size == 3) {
            inv = Bukkit.createInventory(null, 27, Component.translatable("tempBackpack3"));
            ItemStack[] is;
            is = Helper.itemStackArrayFromBase64(
                    App.main.getConfig().getString(p.getUniqueId() + ".backpack.contents.goldbackpack"));
            inv.setContents(is);
        } else if (size == 4) {
            inv = Bukkit.createInventory(null, 36, Component.translatable("tempBackpack4"));
            ItemStack[] is;
            is = Helper.itemStackArrayFromBase64(
                    App.main.getConfig().getString(p.getUniqueId() + ".backpack.contents.diamondbackpack"));
            inv.setContents(is);
        }

        for (ItemStack is : inv.getContents()) {
            if (is != null) {
                if (is.isSimilar(i)) {
                    int iscount = is.getAmount();
                    int itemcount = i.getAmount();
                    if (is.getAmount() == is.getMaxStackSize()) {
                        // nix tun
                    } else {
                        if (iscount + itemcount > is.getMaxStackSize()) {

                            is.setAmount(is.getMaxStackSize());

                            i.subtract(is.getMaxStackSize() - (itemcount + iscount - is.getMaxStackSize()));

                            // PLAYSOUND
                            Bukkit.getServer().getWorlds().get(0).playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP,
                                    0.25F, 1.8F);

                        } else {
                            is.setAmount(iscount + itemcount);
                            i.setAmount(0);
                            // PLAYSOUND
                            Bukkit.getServer().getWorlds().get(0).playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP,
                                    0.25F, 1.8F);
                        }
                    }
                }
            } else {
                freespace = true;
            }

        }

        if (freespace) {
            inv.setItem(inv.firstEmpty(), i);
            i.setAmount(0);
            // PLAYSOUND
            Bukkit.getServer().getWorlds().get(0).playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP, 0.25F, 1.8F);
        }

        if (size == 1) {
            App.main.getConfig().set(p.getUniqueId() + ".backpack.contents.leatherbackpack",
                    Helper.itemStackArrayToBase64(inv.getContents()));
        } else if (size == 2) {
            App.main.getConfig().set(p.getUniqueId() + ".backpack.contents.ironbackpack",
                    Helper.itemStackArrayToBase64(inv.getContents()));
        } else if (size == 3) {
            App.main.getConfig().set(p.getUniqueId() + ".backpack.contents.goldbackpack",
                    Helper.itemStackArrayToBase64(inv.getContents()));
        } else if (size == 4) {
            App.main.getConfig().set(p.getUniqueId() + ".backpack.contents.diamondbackpack",
                    Helper.itemStackArrayToBase64(inv.getContents()));
        }
        App.main.saveConfig();
    }

    @EventHandler
    public void onBackpackUse(PlayerInteractEvent e) {
        if (e.getAction() == Action.LEFT_CLICK_AIR || e.getAction() == Action.LEFT_CLICK_BLOCK) {
            return;
        }
        if (e.getPlayer().getInventory().getItemInOffHand() != null
                && e.getPlayer().getInventory().getItemInOffHand().getItemMeta() != null) {
            if (e.getPlayer().getInventory().getItemInOffHand().getItemMeta().getPersistentDataContainer()
                    .has(App.main.nsk, PersistentDataType.STRING)
                    || e.getPlayer().getInventory().getItemInOffHand().getItemMeta().getPersistentDataContainer()
                            .has(App.main.nsk2, PersistentDataType.STRING)
                    || e.getPlayer().getInventory().getItemInOffHand().getItemMeta().getPersistentDataContainer()
                            .has(App.main.nsk3, PersistentDataType.STRING)
                    || e.getPlayer().getInventory().getItemInOffHand().getItemMeta().getPersistentDataContainer()
                            .has(App.main.nsk4, PersistentDataType.STRING)) {
                e.setCancelled(true);
                return;
            }
        }
        ItemStack is = e.getPlayer().getInventory().getItemInOffHand();
        if (e.getPlayer().getInventory().getItemInMainHand() != null
                && e.getPlayer().getInventory().getItemInMainHand().getItemMeta() != null) {
            if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                    .has(App.main.nsk, PersistentDataType.STRING)
                    && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                            .get(App.main.nsk, PersistentDataType.STRING).toString().equals("R3S_kleiner_Rucksack")) {
                if (e.getAction() == Action.RIGHT_CLICK_AIR || (e.getAction() == Action.RIGHT_CLICK_BLOCK
                        && (!App.helper.isInteractable(e.getClickedBlock()))
                        || e.getClickedBlock() != null && (App.helper.isInteractable(e.getClickedBlock())
                                && (e.getClickedBlock().getBlockData() != null
                                        && (e.getClickedBlock().getBlockData() instanceof Stairs
                                                || e.getClickedBlock().getBlockData() instanceof Fence))))) {
                    // inv = Bukkit.createInventory(null, 9, Component.translatable("Kleiner
                    // Rucksack"));
                    hm.put(e.getPlayer(), Bukkit.createInventory(null, 9, Component.translatable("Kleiner Rucksack")));
                    // e.getPlayer().openInventory(inv);

                    e.setCancelled(true);
                    e.getPlayer().getInventory().setItemInOffHand(new ItemStack(Material.AIR));

                    e.getPlayer().openInventory(hm.get(e.getPlayer()));

                    Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                        @Override
                        public void run() {
                            e.getPlayer().getInventory().setItemInOffHand(is);
                        }
                    }, 3L);

                }
            } else if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                    .has(App.main.nsk2, PersistentDataType.STRING)
                    && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                            .get(App.main.nsk2, PersistentDataType.STRING).toString().equals("R3S_Rucksack")) {
                if (e.getAction() == Action.RIGHT_CLICK_AIR || (e.getAction() == Action.RIGHT_CLICK_BLOCK
                        && (!App.helper.isInteractable(e.getClickedBlock()))
                        || (App.helper.isInteractable(e.getClickedBlock())
                                && (e.getClickedBlock().getBlockData() != null
                                        && (e.getClickedBlock().getBlockData() instanceof Stairs
                                                || e.getClickedBlock().getBlockData() instanceof Fence))))) { // inv2 =
                                                                                                              // Bukkit.createInventory(null,
                                                                                                              // 18,
                                                                                                              // Component.translatable("Rucksack"));
                    hm2.put(e.getPlayer(), Bukkit.createInventory(null, 18, Component.translatable("Rucksack")));
                    // e.getPlayer().openInventory(inv2);
                    e.setCancelled(true);
                    e.getPlayer().getInventory().setItemInOffHand(new ItemStack(Material.AIR));
                    e.getPlayer().openInventory(hm2.get(e.getPlayer()));
                    Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                        @Override
                        public void run() {
                            e.getPlayer().getInventory().setItemInOffHand(is);
                        }
                    }, 3L);
                }
            } else if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                    .has(App.main.nsk3, PersistentDataType.STRING)
                    && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                            .get(App.main.nsk3, PersistentDataType.STRING).toString().equals("R3S_großer_Rucksack")) {
                if (e.getAction() == Action.RIGHT_CLICK_AIR || (e.getAction() == Action.RIGHT_CLICK_BLOCK
                        && (!App.helper.isInteractable(e.getClickedBlock()))
                        || (App.helper.isInteractable(e.getClickedBlock())
                                && (e.getClickedBlock().getBlockData() != null
                                        && (e.getClickedBlock().getBlockData() instanceof Stairs
                                                || e.getClickedBlock().getBlockData() instanceof Fence))))) { // inv3 =
                                                                                                              // Bukkit.createInventory(null,
                                                                                                              // 27,
                                                                                                              // Component.translatable("Großer
                    // Rucksack"));
                    hm3.put(e.getPlayer(), Bukkit.createInventory(null, 27, Component.translatable("Großer Rucksack")));
                    // e.getPlayer().openInventory(inv3);
                    e.setCancelled(true);
                    e.getPlayer().getInventory().setItemInOffHand(new ItemStack(Material.AIR));
                    e.getPlayer().openInventory(hm3.get(e.getPlayer()));
                    Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                        @Override
                        public void run() {
                            e.getPlayer().getInventory().setItemInOffHand(is);
                        }
                    }, 3L);
                }
            } else if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                    .has(App.main.nsk4, PersistentDataType.STRING)
                    && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                            .get(App.main.nsk4, PersistentDataType.STRING).toString().equals("R3S_riesiger_Rucksack")) {
                if (e.getAction() == Action.RIGHT_CLICK_AIR || (e.getAction() == Action.RIGHT_CLICK_BLOCK
                        && (!App.helper.isInteractable(e.getClickedBlock()))
                        || (App.helper.isInteractable(e.getClickedBlock())
                                && (e.getClickedBlock().getBlockData() != null
                                        && (e.getClickedBlock().getBlockData() instanceof Stairs
                                                || e.getClickedBlock().getBlockData() instanceof Fence))))) { // inv4 =
                                                                                                              // Bukkit.createInventory(null,
                                                                                                              // 36,
                                                                                                              // Component.translatable("Riesiger
                    // Rucksack"));
                    hm4.put(e.getPlayer(),
                            Bukkit.createInventory(null, 36, Component.translatable("Riesiger Rucksack")));
                    e.setCancelled(true);
                    e.getPlayer().getInventory().setItemInOffHand(new ItemStack(Material.AIR));
                    e.getPlayer().openInventory(hm4.get(e.getPlayer()));
                    // e.getPlayer().openInventory(inv4);
                    Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                        @Override
                        public void run() {
                            e.getPlayer().getInventory().setItemInOffHand(is);
                        }
                    }, 3L);
                }
            }
        }

    }

    @EventHandler
    public void onBackpackClose(InventoryCloseEvent e) {
        if (e.getInventory() == hm.get(e.getPlayer())) {
            if (!App.main.getConfig().contains(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack")) {
                App.main.getConfig().createSection(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack");
            }
            App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack",
                    Helper.itemStackArrayToBase64(e.getInventory().getContents()));
            App.main.saveConfig();
        } else if (e.getInventory() == hm2.get(e.getPlayer())) {
            if (!App.main.getConfig().contains(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack")) {
                App.main.getConfig().createSection(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack");
            }
            App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack",
                    Helper.itemStackArrayToBase64(e.getInventory().getContents()));
            App.main.saveConfig();
        } else if (e.getInventory() == hm3.get(e.getPlayer())) {
            if (!App.main.getConfig().contains(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack")) {
                App.main.getConfig().createSection(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack");
            }
            App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack",
                    Helper.itemStackArrayToBase64(e.getInventory().getContents()));
            App.main.saveConfig();
        } else if (e.getInventory() == hm4.get(e.getPlayer())) {
            if (!App.main.getConfig().contains(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack")) {
                App.main.getConfig().createSection(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack");
            }
            App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack",
                    Helper.itemStackArrayToBase64(e.getInventory().getContents()));
            App.main.saveConfig();
        }
    }

    @EventHandler
    public void onDeath(PlayerDeathEvent e) throws IllegalArgumentException, IOException {
        e.deathMessage(null);
        for (ItemStack is : e.getPlayer().getInventory().getContents()) {
            if (is == null || !is.hasItemMeta() || is.getItemMeta().getPersistentDataContainer() == null) {
                // return;
            }

            else {
                if (is.getItemMeta().getPersistentDataContainer().has(App.main.nsk, PersistentDataType.STRING)) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack")) {
                        Inventory inv = Bukkit.createInventory(null, 9,
                                Component.translatable("Kleiner Rucksack DEAD"));
                        inv.setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack")));
                        for (ItemStack bis : inv.getContents()) {
                            if (bis != null) {
                                e.getPlayer().getWorld().dropItem(e.getPlayer().getLocation(), bis);
                            }

                        }

                        App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack",
                                Helper.itemStackArrayToBase64(new ItemStack[] {}));

                        App.main.saveConfig();
                    }
                } else if (is.getItemMeta().getPersistentDataContainer().has(App.main.nsk2,
                        PersistentDataType.STRING)) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack")) {
                        Inventory inv = Bukkit.createInventory(null, 18, Component.translatable("Rucksack DEAD"));
                        inv.setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack")));
                        for (ItemStack bis : inv.getContents()) {
                            if (bis != null) {
                                e.getPlayer().getWorld().dropItem(e.getPlayer().getLocation(), bis);
                            }

                        }
                        App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack",
                                Helper.itemStackArrayToBase64(new ItemStack[] {}));
                        App.main.saveConfig();
                    }
                } else if (is.getItemMeta().getPersistentDataContainer().has(App.main.nsk3,
                        PersistentDataType.STRING)) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack")) {
                        Inventory inv = Bukkit.createInventory(null, 27,
                                Component.translatable("Großer Rucksack DEAD"));
                        inv.setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack")));
                        for (ItemStack bis : inv.getContents()) {
                            if (bis != null) {
                                e.getPlayer().getWorld().dropItem(e.getPlayer().getLocation(), bis);
                            }

                        }
                        App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack",
                                Helper.itemStackArrayToBase64(new ItemStack[] {}));
                        App.main.saveConfig();
                    }
                } else if (is.getItemMeta().getPersistentDataContainer().has(App.main.nsk4,
                        PersistentDataType.STRING)) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack")) {
                        Inventory inv = Bukkit.createInventory(null, 36,
                                Component.translatable("Riesiger Rucksack DEAD"));
                        inv.setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack")));
                        for (ItemStack bis : inv.getContents()) {
                            if (bis != null) {
                                e.getPlayer().getWorld().dropItem(e.getPlayer().getLocation(), bis);
                            }

                        }
                        App.main.getConfig().set(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack",
                                Helper.itemStackArrayToBase64(new ItemStack[] {}));
                        App.main.saveConfig();
                    }
                }
            }
        }
    }

    @EventHandler
    public void onBackpackOpen(InventoryOpenEvent e) throws IOException {
        try {
            if (e.getView().title().equals(Component.translatable("Kleiner Rucksack"))
                    || e.getView().title().equals(Component.translatable("Rucksack"))
                    || e.getView().title().equals(Component.translatable("Großer Rucksack"))
                    || e.getView().title().equals(Component.translatable("Riesiger Rucksack"))) {
                if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                        .has(App.main.nsk, PersistentDataType.STRING)
                        && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                                .get(App.main.nsk, PersistentDataType.STRING).toString()
                                .equals("R3S_kleiner_Rucksack")) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack")) {
                        e.getInventory().setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.leatherbackpack")));
                    }
                } else if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                        .has(App.main.nsk2, PersistentDataType.STRING)
                        && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                                .get(App.main.nsk2, PersistentDataType.STRING).toString().equals("R3S_Rucksack")) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack")) {
                        e.getInventory().setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.ironbackpack")));
                    }
                } else if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                        .has(App.main.nsk3, PersistentDataType.STRING)
                        && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                                .get(App.main.nsk3, PersistentDataType.STRING).toString()
                                .equals("R3S_großer_Rucksack")) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack")) {
                        e.getInventory().setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.goldbackpack")));
                    }
                } else if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                        .has(App.main.nsk4, PersistentDataType.STRING)
                        && e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                                .get(App.main.nsk4, PersistentDataType.STRING).toString()
                                .equals("R3S_riesiger_Rucksack")) {
                    if (App.main.getConfig()
                            .contains(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack")) {
                        e.getInventory().setContents(Helper.itemStackArrayFromBase64(App.main.getConfig()
                                .getString(e.getPlayer().getUniqueId() + ".backpack.contents.diamondbackpack")));
                    }
                }
            }
        } catch (Exception ex) {
        }
    }

    @EventHandler
    public void onInvMove(InventoryDragEvent e) {
        if (e.getInventory() != null && e.getInventory().getType() == InventoryType.CHEST) {
            if (e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Kleiner Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Großer Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title()
                            .equals(Component.translatable("Riesiger Rucksack"))) {

                for (Object s : e.getRawSlots()) {
                    if ((int) s > e.getWhoClicked().getOpenInventory().getTopInventory().getSize()) {

                        return;
                    }
                }

                if (e.getOldCursor() != null) {
                    if (e.getOldCursor().equals(App.main.backPack) || e.getOldCursor().equals(App.main.backPack2)
                            || e.getOldCursor().equals(App.main.backPack3)
                            || e.getOldCursor().equals(App.main.backPack4)) {
                        e.setCancelled(true);
                    }
                }
            }

        }

    }

    @EventHandler
    public void onInvMove(InventoryClickEvent e) {
        if (e.getClickedInventory() != null && e.getClickedInventory().getType() == InventoryType.CHEST) {
            if (e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Kleiner Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Großer Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title()
                            .equals(Component.translatable("Riesiger Rucksack"))) {

                if (/*
                     * e.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD
                     * ||
                     */e.getAction() == InventoryAction.HOTBAR_SWAP) {

                    if (e.getHotbarButton() != -1) {// evtl auch schauen ob titel, da es sonst auch nicht in truhe
                                                    // gepackt werden kann, evtl aber auch schon oben gekläört

                        if (e.getView().getBottomInventory().getItem(e.getHotbarButton()) != null && (e.getView()
                                .getBottomInventory().getItem(e.getHotbarButton()).equals(App.main.backPack)
                                || e.getView().getBottomInventory().getItem(e.getHotbarButton())
                                        .equals(App.main.backPack2)
                                || e.getView().getBottomInventory().getItem(e.getHotbarButton())
                                        .equals(App.main.backPack3)
                                || e.getView().getBottomInventory().getItem(e.getHotbarButton())
                                        .equals(App.main.backPack4))) {
                            e.setCancelled(true);
                            return;
                        }

                    }

                    if (e.getHotbarButton() != -1
                            && e.getWhoClicked().getInventory().getItem(e.getHotbarButton()) != null) {
                        if (e.getWhoClicked().getInventory().getItem(e.getHotbarButton())
                                .equals(App.main.backPack)
                                || e.getWhoClicked().getInventory().getItem(e.getHotbarButton())
                                        .equals(App.main.backPack2)
                                || e.getWhoClicked().getInventory().getItem(e.getHotbarButton())
                                        .equals(App.main.backPack3)
                                || e.getWhoClicked().getInventory().getItem(e.getHotbarButton())
                                        .equals(App.main.backPack4)) {
                            e.setCancelled(true);
                            return;
                        }
                    } else {
                        if (e.getWhoClicked().getInventory().getItemInOffHand() != null && (e.getWhoClicked()
                                .getInventory().getItemInOffHand().equals(App.main.backPack)
                                || e.getWhoClicked().getInventory().getItemInOffHand().equals(App.main.backPack2)
                                || e.getWhoClicked().getInventory().getItemInOffHand().equals(App.main.backPack3)
                                || e.getWhoClicked().getInventory().getItemInOffHand().equals(App.main.backPack4))) {
                            ItemStack bpIs = e.getWhoClicked().getInventory().getItemInOffHand();
                            e.setCancelled(true);
                            e.getWhoClicked().getInventory().setItemInOffHand(bpIs);
                        }
                    }

                }
                if (e.getCursor() != null) {
                    if (e.getCursor().equals(App.main.backPack) || e.getCursor().equals(App.main.backPack2)
                            || e.getCursor().equals(App.main.backPack3) || e.getCursor().equals(App.main.backPack4)) {
                        e.setCancelled(true);
                    }
                }

            }
        }

        if (e.isShiftClick()) {
            if (e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Kleiner Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Großer Rucksack"))
                    || e.getWhoClicked().getOpenInventory().title()
                            .equals(Component.translatable("Riesiger Rucksack"))) {
                if (e.getClickedInventory() != null && e.getClickedInventory().getItem(e.getSlot()) != null) {
                    if (e.getClickedInventory() != null && e.getClickedInventory().getItem(e.getSlot()) != null) {
                        if (e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                .getPersistentDataContainer() != null) {
                            if (e.getClickedInventory().getItem(e.getSlot()).getItemMeta().getPersistentDataContainer()
                                    .get(App.main.nsk, PersistentDataType.STRING) != null
                                    && e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                            .getPersistentDataContainer().get(App.main.nsk, PersistentDataType.STRING)
                                            .toString().equals("R3S_kleiner_Rucksack")
                                    || e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                            .getPersistentDataContainer()
                                            .get(App.main.nsk2, PersistentDataType.STRING) != null
                                            && e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                                    .getPersistentDataContainer()
                                                    .get(App.main.nsk2, PersistentDataType.STRING).toString()
                                                    .equals("R3S_Rucksack")
                                    || e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                            .getPersistentDataContainer()
                                            .get(App.main.nsk3, PersistentDataType.STRING) != null
                                            && e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                                    .getPersistentDataContainer()
                                                    .get(App.main.nsk3, PersistentDataType.STRING).toString()
                                                    .equals("R3S_großer_Rucksack")
                                    || e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                            .getPersistentDataContainer()
                                            .get(App.main.nsk4, PersistentDataType.STRING) != null
                                            && e.getClickedInventory().getItem(e.getSlot()).getItemMeta()
                                                    .getPersistentDataContainer()
                                                    .get(App.main.nsk4, PersistentDataType.STRING).toString()
                                                    .equals("R3S_riesiger_Rucksack")) {
                                e.setCancelled(true);
                            }
                        }
                    }
                }
            }
        }
    }

    @EventHandler
    public void craftBlocker(PrepareItemCraftEvent evt) {

        if (evt.getRecipe() != null && evt.getRecipe().getResult() != null) {
            if (!evt.getRecipe().getResult().equals(App.main.backPack)
                    && !evt.getRecipe().getResult().equals(App.main.backPack2)
                    && !evt.getRecipe().getResult().equals(App.main.backPack3)
                    && !evt.getRecipe().getResult().equals(App.main.backPack4)) {
                if (evt.getInventory().containsAtLeast(App.main.backPack, 1)
                        || evt.getInventory().containsAtLeast(App.main.backPack2, 1)
                        || evt.getInventory().containsAtLeast(App.main.backPack3, 1)
                        || evt.getInventory().containsAtLeast(App.main.backPack4, 1)) {
                    evt.getInventory().setResult(null);
                }
            }

        }
    }

    @EventHandler
    public void ovenBlocker(FurnaceBurnEvent e) {

        if (e.getFuel() != null && e.getFuel().equals(App.main.backPack) || e.getFuel().equals(App.main.backPack2)
                || e.getFuel().equals(App.main.backPack3) || e.getFuel().equals(App.main.backPack4)) {
            e.setCancelled(true);
        }
    }

    @EventHandler
    public void onTraderDeath(EntityDeathEvent event) {
        if (event.getEntityType() == EntityType.WANDERING_TRADER) {
            WanderingTrader wt = (WanderingTrader) event.getEntity();
            List<ItemStack> is = new ArrayList<ItemStack>();
            for (MerchantRecipe mr : wt.getRecipes()) {
                if (mr != null) {
                    is.add(mr.getResult());
                }
            }
            int randomIndex = (new Random()).nextInt(is.size());
            ItemStack randomElement = is.get(randomIndex);
            wt.getLocation().getWorld().dropItemNaturally(wt.getLocation(), new ItemStack(randomElement.getType(), 1));
            Random r = new Random();
            int result = r.nextInt(101);
            if (result >= 90) { // 10% = 2 Smaragde
                wt.getLocation().getWorld().dropItemNaturally(wt.getLocation(), new ItemStack(Material.EMERALD, 2));
            } else if (result < 90 && result >= 75) { // 15% = 1 Smaragd
                wt.getLocation().getWorld().dropItemNaturally(wt.getLocation(), new ItemStack(Material.EMERALD, 1));
            } // 75% = kein smaragd
        }
    }

    @EventHandler
    public void copperNerf(BlockBreakEvent e) {

        if (e.getPlayer().getInventory().getItemInMainHand() == null
                || (e.getBlock().getType().equals(Material.COPPER_ORE) == false
                        && e.getBlock().getType().equals(Material.DEEPSLATE_COPPER_ORE) == false)) {
            return;
        }
        if (e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.STONE_PICKAXE) ||
                e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.IRON_PICKAXE) ||
                e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.GOLDEN_PICKAXE) ||
                e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.DIAMOND_PICKAXE) ||
                e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.NETHERITE_PICKAXE)) {
            e.setCancelled(true);
            Location loc = e.getBlock().getLocation();
            e.getBlock().breakNaturally(new ItemStack(Material.AIR));
            Bukkit.getWorlds().get(0).dropItem(loc, new ItemStack(Material.RAW_COPPER, 1));

        }
    }

    @EventHandler
    public void axoNerf(EntityTargetLivingEntityEvent e) {
        if (e.getEntity() instanceof org.bukkit.entity.Axolotl
                && (e.getTarget() instanceof Fish || e.getTarget() instanceof Squid)) {
            e.setTarget(null);
            Axolotl ax = (Axolotl) e.getEntity();
            MemoryKey<Boolean> mk = MemoryKey.HAS_HUNTING_COOLDOWN;
            ax.setMemory(mk, true);
            return;
        }

    }

    @EventHandler
    public void clearInventroy(InventoryClickEvent e) {
        if (e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Kleiner Rucksack"))
                || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Rucksack"))
                || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Großer Rucksack"))
                || e.getWhoClicked().getOpenInventory().title().equals(Component.translatable("Riesiger Rucksack"))) {

            if (e.getClick() == ClickType.DOUBLE_CLICK) {
                if (e.getClickedInventory().getType().equals(InventoryType.PLAYER)) {

                    int i = 0;
                    for (ItemStack is : e.getWhoClicked().getOpenInventory().getTopInventory().getStorageContents()) {
                        if (e.getWhoClicked().getInventory().firstEmpty() == -1) {
                            return;
                        }
                        if (is != null) {
                            e.getWhoClicked().getInventory().addItem(is);
                            e.getWhoClicked().getOpenInventory().getTopInventory().setItem(i, null);
                        }
                        i++;
                    }

                } else {
                    // WENN IHC OPEN KLICKE ALLES VON INV NACH OPEN

                    int i = 0;
                    for (ItemStack is : e.getWhoClicked().getInventory().getStorageContents()) {
                        if (e.getWhoClicked().getOpenInventory().getTopInventory().firstEmpty() == -1) {
                            return;
                        }

                        if (is != null) {

                            if (is.getItemMeta() != null && is.getItemMeta().getPersistentDataContainer() != null) {

                                if (is.getItemMeta().getPersistentDataContainer().has(App.main.nsk,
                                        PersistentDataType.STRING)
                                        || is.getItemMeta().getPersistentDataContainer().has(App.main.nsk2,
                                                PersistentDataType.STRING)
                                        || is.getItemMeta().getPersistentDataContainer().has(App.main.nsk3,
                                                PersistentDataType.STRING)
                                        || is.getItemMeta().getPersistentDataContainer().has(App.main.nsk4,
                                                PersistentDataType.STRING)
                                        || (e.getWhoClicked().getOpenInventory().getTopInventory().getType()
                                                .equals(InventoryType.SHULKER_BOX)
                                                && is.getType().toString().contains("SHULKER_BOX"))) {

                                } else {
                                    e.getWhoClicked().getOpenInventory().getTopInventory().addItem(is);
                                    e.getWhoClicked().getInventory().setItem(i, null);
                                }

                            }

                        }
                        i++;
                    }

                }
            }
            return;
        }

        if (e.getClick().toString().equals("DOUBLE_CLICK") && e.getCursor().getType().equals(Material.AIR)
                && e.getCurrentItem().getType().equals(Material.AIR)
                && e.getClickedInventory().getType().equals(InventoryType.PLAYER)) {
            if (e.getWhoClicked().getOpenInventory().getTopInventory().getType() == InventoryType.CHEST
                    || e.getWhoClicked().getOpenInventory().getTopInventory().getType() == InventoryType.ENDER_CHEST
                    || e.getWhoClicked().getOpenInventory().getTopInventory().getType() == InventoryType.SHULKER_BOX) {
                // WENN IN INVENTAR GEKLICKT SCHIEBE VON OPEN NACH INV
                int i = 0;
                for (ItemStack is : e.getWhoClicked().getOpenInventory().getTopInventory().getStorageContents()) {
                    if (e.getWhoClicked().getInventory().firstEmpty() == -1) {
                        return;
                    }
                    if (is != null) {
                        e.getWhoClicked().getOpenInventory().getTopInventory().setItem(i, null);
                        e.getWhoClicked().getInventory().addItem(is);
                    }
                    i++;
                }
            }

        } else if (e.getClick().toString().equals("DOUBLE_CLICK") && e.getCursor().getType().equals(Material.AIR)
                && e.getCurrentItem().getType().equals(Material.AIR) &&
                (e.getClickedInventory().getType().equals(InventoryType.CHEST)
                        || e.getWhoClicked().getOpenInventory().getTopInventory()
                                .getType() == InventoryType.ENDER_CHEST)) {

            // WENN OPEN GEKLICKT SCHIEBE VON INV NACH OPEN
            int i = 0;
            for (ItemStack is : e.getWhoClicked().getInventory().getStorageContents()) {
                if (e.getWhoClicked().getOpenInventory().getTopInventory().firstEmpty() == -1) {
                    return;
                }
                if (is != null) {
                    e.getWhoClicked().getInventory().setItem(i, null);
                    e.getWhoClicked().getOpenInventory().getTopInventory().addItem(is);
                }
                i++;
            }
        } else if (e.getClick().toString().equals("DOUBLE_CLICK") && e.getCursor().getType().equals(Material.AIR)
                && e.getCurrentItem().getType().equals(Material.AIR)
                && e.getWhoClicked().getOpenInventory().getTopInventory().getType() == InventoryType.SHULKER_BOX) {
            int i = 0;
            for (ItemStack is : e.getWhoClicked().getInventory().getStorageContents()) {
                if (e.getWhoClicked().getOpenInventory().getTopInventory().firstEmpty() == -1) {
                    return;
                }
                if (is != null && (e.getWhoClicked().getOpenInventory().getTopInventory().getType()
                        .equals(InventoryType.SHULKER_BOX) && !is.getType().toString().contains("SHULKER_BOX"))) {
                    e.getWhoClicked().getInventory().setItem(i, null);
                    e.getWhoClicked().getOpenInventory().getTopInventory().addItem(is);
                }
                i++;
            }
        }
    }
}
