package de.hessj.chestex;

import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;

import de.hessj.helper.Helper.Type;

public class SafeChestListener implements Listener {
    public Boolean lastPlacedIsSafeChest = false;
    public de.hessj.helper.Helper helper= new de.hessj.helper.Helper();

    @EventHandler
    public void onJoin(PlayerJoinEvent e) {
        e.getPlayer().discoverRecipe(App.main.nskLockedChestRecipe);
    }

    @EventHandler
    public void onInteract(PlayerInteractEvent e) {
        if (e.getAction() == Action.RIGHT_CLICK_BLOCK && !helper.isInteractable(e.getClickedBlock())) {
            if (e.getPlayer().getInventory().getItemInMainHand() != null
                    && e.getPlayer().getInventory().getItemInMainHand().hasItemMeta() && e.getPlayer().getInventory()
                            .getItemInMainHand().getItemMeta().getPersistentDataContainer() != null) {
                if (e.getPlayer().getInventory().getItemInMainHand().getItemMeta().getPersistentDataContainer()
                        .has(App.main.nskLockedChest, PersistentDataType.STRING)) {
                    lastPlacedIsSafeChest = true;
                }
            }
        } else if (e.getAction() == Action.RIGHT_CLICK_BLOCK && helper.isInteractable(e.getClickedBlock())) {
            Location loc = e.getClickedBlock().getLocation();
            String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();
            if (App.main.getConfig().getStringList("chests." + e.getPlayer().getUniqueId().toString())
                    .contains(locStr)) {
                // is meine truhe
            } else {
                if (App.main.getConfig().getConfigurationSection("chests") != null) {
                    for (String uuid : App.main.getConfig().getConfigurationSection("chests").getKeys(false)) {
                        List<String> chestList = App.main.getConfig().getStringList("chests." + uuid);
                        if (chestList.contains(locStr)) {
                            e.setCancelled(true);
                            e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR, "[ChestEx] Dies ist nicht deine Truhe!"));
                            return;
                        }
                    }
                }
            }
        }

    }

    @EventHandler
    public void onPlace(BlockPlaceEvent e) {
        if (e.getBlockPlaced().getType().equals(Material.CHEST) && lastPlacedIsSafeChest) {

            Chest chest = (Chest) e.getBlock().getState();

            Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                @Override
                public void run() {

                    InventoryHolder holder = chest.getInventory().getHolder();

                    if (holder instanceof DoubleChest) {
                        DoubleChest doubleChest = ((DoubleChest) holder);
                        Chest leftChest = (Chest) doubleChest.getLeftSide();
                        Chest rightChest = (Chest) doubleChest.getRightSide();

                        // WENN HIER DIE EINE IN CONFIG GEHÖRT PLAYER

                        if (leftChest.getLocation().equals(e.getBlockPlaced().getLocation())) {
                            // rechte checken
                            Location loc = rightChest.getLocation();
                            String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();

                            if (!App.main.getConfig().getStringList("chests." + e.getPlayer().getUniqueId().toString())
                                    .contains(locStr)) {
                                e.getBlockPlaced().setType(Material.AIR);
                                e.setCancelled(true);
                                // HIER
                                if (e.getHand() == EquipmentSlot.OFF_HAND) {
                                    if (e.getPlayer().getInventory().getItemInOffHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInOffHand(
                                                e.getPlayer().getInventory().getItemInOffHand().add(1));
                                    } else {
                                        e.getPlayer().getInventory().setItemInOffHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                } else if (e.getHand() == EquipmentSlot.HAND) {
                                    if (e.getPlayer().getInventory().getItemInMainHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInMainHand(
                                                e.getPlayer().getInventory().getItemInMainHand().add(1));

                                    } else {
                                        e.getPlayer().getInventory().setItemInMainHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                }

                                e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR,                             "[ChestEx] Du kannst diese Truhe nicht mit einer verschlossenen Truhe erweitern!"));
                                return;
                            }

                        } else if (rightChest.getLocation().equals(e.getBlockPlaced().getLocation())) {
                            // linke checken
                            Location loc = leftChest.getLocation();
                            String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();

                            if (!App.main.getConfig().getStringList("chests." + e.getPlayer().getUniqueId().toString())
                                    .contains(locStr)) {
                                e.getBlockPlaced().setType(Material.AIR);
                                e.setCancelled(true);
                                // HIER
                                if (e.getHand() == EquipmentSlot.OFF_HAND) {
                                    if (e.getPlayer().getInventory().getItemInOffHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInOffHand(
                                                e.getPlayer().getInventory().getItemInOffHand().add(1));
                                    } else {
                                        e.getPlayer().getInventory().setItemInOffHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                } else if (e.getHand() == EquipmentSlot.HAND) {
                                    if (e.getPlayer().getInventory().getItemInMainHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInMainHand(
                                                e.getPlayer().getInventory().getItemInMainHand().add(1));

                                    } else {
                                        e.getPlayer().getInventory().setItemInMainHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                }

                                e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR, "[ChestEx] Du kannst diese Truhe nicht mit einer verschlossenen Truhe erweitern!"));
                                return;
                            }
                        }
                    }

                    // HIER IN DING EINTRAGEN
                    Location loc = e.getBlockPlaced().getLocation();
                    List<String> chestList = App.main.getConfig()
                            .getStringList("chests." + e.getPlayer().getUniqueId().toString());
                    chestList.add(loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ());
                    App.main.getConfig().set("chests." + e.getPlayer().getUniqueId().toString(), chestList);

                    App.main.saveConfig();

                    lastPlacedIsSafeChest = false;
                }
            }, 1L);

        } else if (e.getBlockPlaced().getType().equals(Material.CHEST) && !lastPlacedIsSafeChest) {
            Chest chest = (Chest) e.getBlock().getState();

            Bukkit.getScheduler().scheduleSyncDelayedTask(App.main, new Runnable() {
                @Override
                public void run() {

                    InventoryHolder holder = chest.getInventory().getHolder();

                    if (holder instanceof DoubleChest) {
                        DoubleChest doubleChest = ((DoubleChest) holder);
                        Chest leftChest = (Chest) doubleChest.getLeftSide();
                        Chest rightChest = (Chest) doubleChest.getRightSide();

                        // WENN HIER DIE EINE IN CONFIG GEHÖRT PLAYER

                        if (leftChest.getLocation().equals(e.getBlockPlaced().getLocation())) {
                            // rechte checken
                            Location loc = rightChest.getLocation();
                            String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();

                            if (App.main.getConfig().getStringList("chests." + e.getPlayer().getUniqueId().toString())
                                    .contains(locStr)) {
                                e.getBlockPlaced().setType(Material.AIR);
                                e.setCancelled(true);
                                // HIER
                                if (e.getHand() == EquipmentSlot.OFF_HAND) {
                                    if (e.getPlayer().getInventory().getItemInOffHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInOffHand(
                                                e.getPlayer().getInventory().getItemInOffHand().add(1));
                                    } else {
                                        e.getPlayer().getInventory().setItemInOffHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                } else if (e.getHand() == EquipmentSlot.HAND) {
                                    if (e.getPlayer().getInventory().getItemInMainHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInMainHand(
                                                e.getPlayer().getInventory().getItemInMainHand().add(1));

                                    } else {
                                        e.getPlayer().getInventory().setItemInMainHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                }
                                e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR, "[ChestEx] Du kannst eine verschlossene Truhe nicht mit einer anderen Truhe erweitern!"));

                            }

                        } else if (rightChest.getLocation().equals(e.getBlockPlaced().getLocation())) {
                            // linke checken
                            Location loc = leftChest.getLocation();
                            String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();

                            if (App.main.getConfig().getStringList("chests." + e.getPlayer().getUniqueId().toString())
                                    .contains(locStr)) {
                                e.getBlockPlaced().setType(Material.AIR);
                                e.setCancelled(true);
                                // HIER
                                if (e.getHand() == EquipmentSlot.OFF_HAND) {
                                    if (e.getPlayer().getInventory().getItemInOffHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInOffHand(
                                                e.getPlayer().getInventory().getItemInOffHand().add(1));
                                    } else {
                                        e.getPlayer().getInventory().setItemInOffHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                } else if (e.getHand() == EquipmentSlot.HAND) {
                                    if (e.getPlayer().getInventory().getItemInMainHand().getAmount() > 0) {
                                        e.getPlayer().getInventory().setItemInMainHand(
                                                e.getPlayer().getInventory().getItemInMainHand().add(1));
                                    } else {
                                        e.getPlayer().getInventory().setItemInMainHand(App.main.lockedChest);
                                        e.getPlayer().updateInventory();
                                    }
                                }
                                e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR, "[ChestEx] Du kannst eine verschlossene Truhe nicht mit einer anderen Truhe erweitern!"));
                            }
                        }
                    }
                }
            }, 1L);

        }

    }

    @EventHandler
    public void onEntityExplodeEvent(EntityExplodeEvent event) {
        List<Block> safelist = new ArrayList<Block>();
        for (Block block : event.blockList()) {
            if (block.getType() == Material.CHEST) {
                if (App.main.getConfig().getConfigurationSection("chests") != null) {
                    Location loc = block.getLocation();
                    String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();
                    for (String uuid : App.main.getConfig().getConfigurationSection("chests").getKeys(false)) {
                        List<String> chestList = App.main.getConfig().getStringList("chests." + uuid);
                        if (chestList.contains(locStr)) {
                            safelist.add(block);
                        }
                    }
                }
            }
        }
        for (Block b : safelist) {
            event.blockList().remove(b);
        }
    }

    @EventHandler
    public void onDestroy(BlockBreakEvent e) {
        if (!e.getBlock().getType().equals(Material.CHEST)) {
            return;
        }

        Location loc = e.getBlock().getLocation();
        String locStr = loc.getBlockX() + "~" + loc.getBlockY() + "~" + loc.getBlockZ();
        if (App.main.getConfig().getStringList("chests." + e.getPlayer().getUniqueId().toString()).contains(locStr)) {
            List<String> chestList = App.main.getConfig()
                    .getStringList("chests." + e.getPlayer().getUniqueId().toString());
            chestList.remove(locStr);
            App.main.getConfig().set("chests." + e.getPlayer().getUniqueId().toString(), chestList);
            App.main.saveConfig();

            e.setCancelled(true);

            Chest c = (Chest) e.getBlock().getState();

            for (ItemStack is : c.getBlockInventory()) {
                if (is != null) {

                    e.getBlock().getWorld().dropItemNaturally(loc, is);
                }
            }
            e.getBlock().setType(Material.AIR);

            e.getBlock().getWorld().dropItem(loc, App.main.lockedChest);
        } else {
            if (App.main.getConfig().getConfigurationSection("chests") != null) {
                for (String uuid : App.main.getConfig().getConfigurationSection("chests").getKeys(false)) {
                    List<String> chestList = App.main.getConfig().getStringList("chests." + uuid);
                    if (chestList.contains(locStr)) {
                        e.setCancelled(true);
                        e.getPlayer().sendMessage(helper.R3SMessage(Type.ERROR, "[ChestEx] Dies ist nicht deine Truhe!"));
                        return;
                    }
                }
            }
        }

    }
}