Search in sources :

Example 36 with EntityType

use of org.bukkit.entity.EntityType in project askyblock by tastybento.

the class Challenges method hasRequired.

/**
 * Checks if a player has enough for a challenge. Supports two types of
 * checks, inventory and island. Removes items if required.
 *
 * @param player
 * @param challenge
 * @param type
 * @return true if the player has everything required
 */
public boolean hasRequired(final Player player, final String challenge, final String type) {
    // Check money
    double moneyReq = 0D;
    if (Settings.useEconomy) {
        moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney", 0D);
        if (moneyReq > 0D) {
            if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) {
                Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems);
                String desc = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge + ".description").replace("[label]", Settings.ISLANDCOMMAND));
                List<String> result = new ArrayList<String>();
                if (desc.contains("|")) {
                    result.addAll(Arrays.asList(desc.split("\\|")));
                } else {
                    result.add(desc);
                }
                for (String line : result) {
                    Util.sendMessage(player, ChatColor.RED + line);
                }
                return false;
            }
        }
    }
    final String reqList = getChallengeConfig().getString("challenges.challengeList." + challenge + ".requiredItems");
    // standard items can be collected
    if (type.equalsIgnoreCase("inventory")) {
        List<ItemStack> toBeRemoved = new ArrayList<ItemStack>();
        Material reqItem;
        int reqAmount = 0;
        if (!reqList.isEmpty()) {
            for (final String s : reqList.split(" ")) {
                final String[] part = s.split(":");
                // Material:Qty
                if (part.length == 2) {
                    try {
                        // Correct some common mistakes
                        if (part[0].equalsIgnoreCase("potato")) {
                            part[0] = "POTATO_ITEM";
                        } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                            part[0] = "BREWING_STAND_ITEM";
                        } else if (part[0].equalsIgnoreCase("carrot")) {
                            part[0] = "CARROT_ITEM";
                        } else if (part[0].equalsIgnoreCase("cauldron")) {
                            part[0] = "CAULDRON_ITEM";
                        } else if (part[0].equalsIgnoreCase("skull")) {
                            part[0] = "SKULL_ITEM";
                        }
                        // TODO: add netherwart vs. netherstalk?
                        if (StringUtils.isNumeric(part[0])) {
                            reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                        } else {
                            reqItem = Material.getMaterial(part[0].toUpperCase());
                        }
                        reqAmount = Integer.parseInt(part[1]);
                        ItemStack item = new ItemStack(reqItem);
                        if (DEBUG) {
                            plugin.getLogger().info("DEBUG: required item = " + reqItem.toString());
                            plugin.getLogger().info("DEBUG: item amount = " + reqAmount);
                        }
                        if (!player.getInventory().contains(reqItem)) {
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: item not in inventory");
                            return false;
                        } else {
                            // check amount
                            int amount = 0;
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: Amount in inventory = " + player.getInventory().all(reqItem).size());
                            // enough required items
                            for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem).entrySet()) {
                                // Get the item
                                ItemStack i = en.getValue();
                                // If the item is enchanted, skip - it doesn't count
                                if (!i.getEnchantments().isEmpty()) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: item has enchantment - doesn't count");
                                    continue;
                                }
                                // in the same way, they need adding too...
                                if (i.getDurability() == 0 || (reqItem == Material.MAP && i.getType() == Material.MAP)) {
                                    // amount += i.getAmount();
                                    if ((amount + i.getAmount()) < reqAmount) {
                                        // Remove all of this item stack - clone
                                        // otherwise it will keep a reference to
                                        // the
                                        // original
                                        toBeRemoved.add(i.clone());
                                        amount += i.getAmount();
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: amount is <= req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                    } else if ((amount + i.getAmount()) == reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: amount is = req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                        toBeRemoved.add(i.clone());
                                        amount += i.getAmount();
                                        break;
                                    } else {
                                        // Remove a portion of this item
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: amount is > req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                        item.setAmount(reqAmount - amount);
                                        item.setDurability(i.getDurability());
                                        toBeRemoved.add(item);
                                        amount += i.getAmount();
                                        break;
                                    }
                                }
                            }
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: amount " + amount);
                            if (amount < reqAmount) {
                                return false;
                            }
                        }
                    } catch (Exception e) {
                        plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                        Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                        String materialList = "";
                        boolean hint = false;
                        for (Material m : Material.values()) {
                            materialList += m.toString() + ",";
                            if (m.toString().contains(s.substring(0, 3).toUpperCase())) {
                                plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                                hint = true;
                            }
                        }
                        if (!hint) {
                            plugin.getLogger().severe("Sorry, I have no idea what " + s + " is. Pick from one of these:");
                            plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                        } else {
                            plugin.getLogger().severe("Correct challenges.yml with the correct material.");
                        }
                        return false;
                    }
                } else if (part.length == 3) {
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: Item with durability");
                    // Correct some common mistakes
                    if (part[0].equalsIgnoreCase("potato")) {
                        part[0] = "POTATO_ITEM";
                    } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                        part[0] = "BREWING_STAND_ITEM";
                    } else if (part[0].equalsIgnoreCase("carrot")) {
                        part[0] = "CARROT_ITEM";
                    } else if (part[0].equalsIgnoreCase("cauldron")) {
                        part[0] = "CAULDRON_ITEM";
                    } else if (part[0].equalsIgnoreCase("skull")) {
                        part[0] = "SKULL_ITEM";
                    }
                    if (StringUtils.isNumeric(part[0])) {
                        reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                    } else {
                        reqItem = Material.getMaterial(part[0].toUpperCase());
                    }
                    reqAmount = Integer.parseInt(part[2]);
                    ItemStack item = new ItemStack(reqItem);
                    int reqDurability = 0;
                    boolean entityIsString = false;
                    if (StringUtils.isNumeric(part[1])) {
                        reqDurability = Integer.parseInt(part[1]);
                        item.setDurability((short) reqDurability);
                    } else if (reqItem.equals(Material.MONSTER_EGG)) {
                        entityIsString = true;
                        // non existent
                        reqDurability = -1;
                        try {
                            // Check if this is a string
                            EntityType entityType = EntityType.valueOf(part[1]);
                            NMSAbstraction nms = null;
                            nms = Util.checkVersion();
                            item = nms.getSpawnEgg(entityType, reqAmount);
                        } catch (Exception ex) {
                            plugin.getLogger().severe("Unknown entity type '" + part[1] + "' for MONSTER_EGG in challenge " + challenge);
                            return false;
                        }
                    }
                    // check amount
                    int amount = 0;
                    // enough required items
                    for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem).entrySet()) {
                        // Get the item
                        ItemStack i = en.getValue();
                        if (i.hasItemMeta() && !i.getType().equals(Material.MONSTER_EGG)) {
                            continue;
                        }
                        if (i.getDurability() == reqDurability || (entityIsString && i.getItemMeta().equals(item.getItemMeta()))) {
                            // amount += i.getAmount();
                            if ((amount + i.getAmount()) < reqAmount) {
                                // Remove all of this item stack - clone
                                // otherwise it will keep a reference to
                                // the
                                // original
                                toBeRemoved.add(i.clone());
                                amount += i.getAmount();
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: amount is <= req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                            } else if ((amount + i.getAmount()) == reqAmount) {
                                toBeRemoved.add(i.clone());
                                amount += i.getAmount();
                                break;
                            } else {
                                // Remove a portion of this item
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: amount is > req Remove " + i.toString() + ":" + i.getDurability() + " x " + i.getAmount());
                                item.setAmount(reqAmount - amount);
                                item.setDurability(i.getDurability());
                                toBeRemoved.add(item);
                                amount += i.getAmount();
                                break;
                            }
                        }
                    }
                    if (DEBUG) {
                        plugin.getLogger().info("DEBUG: amount is " + amount);
                        plugin.getLogger().info("DEBUG: req amount is " + reqAmount);
                    }
                    if (amount < reqAmount) {
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: Failure! Insufficient amount of " + item.toString() + " required = " + reqAmount + " actual = " + amount);
                        return false;
                    }
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: before set amount " + item.toString() + ":" + item.getDurability() + " x " + item.getAmount());
                } else if (part.length == 6 && part[0].contains("POTION")) {
                    // Run through player's inventory for the item
                    ItemStack[] playerInv = player.getInventory().getContents();
                    try {
                        reqAmount = Integer.parseInt(part[5]);
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: required amount is " + reqAmount);
                    } catch (Exception e) {
                        plugin.getLogger().severe("Could not parse the quantity of the potion item " + s);
                        return false;
                    }
                    int count = reqAmount;
                    for (ItemStack i : playerInv) {
                        // Catches all POTION, LINGERING_POTION and SPLASH_POTION
                        if (i != null && i.getType().toString().contains("POTION")) {
                            // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
                            if (plugin.getServer().getVersion().contains("(MC: 1.8") || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                                // Test potion
                                Potion potion = null;
                                try {
                                    // This may fail if there are custom potions in the player's inventory
                                    // If so, just skip this item stack.
                                    potion = Potion.fromItemStack(i);
                                } catch (Exception e) {
                                    potion = null;
                                }
                                if (potion != null) {
                                    PotionType potionType = potion.getType();
                                    boolean match = true;
                                    if (DEBUG) {
                                        plugin.getLogger().info("DEBUG: name check " + part[1]);
                                        plugin.getLogger().info("DEBUG: potion = " + potion);
                                        plugin.getLogger().info("DEBUG: potionType = " + potionType);
                                        plugin.getLogger().info("DEBUG: part[1] = " + part[1]);
                                    }
                                    // Name check
                                    if (potionType != null && !part[1].isEmpty()) {
                                        // Custom potions may not have names
                                        if (potionType.name() != null) {
                                            if (!part[1].equalsIgnoreCase(potionType.name())) {
                                                match = false;
                                                if (DEBUG)
                                                    plugin.getLogger().info("DEBUG: name does not match");
                                            } else {
                                                if (DEBUG)
                                                    plugin.getLogger().info("DEBUG: name matches");
                                            }
                                        } else {
                                            plugin.getLogger().severe("Potion type is unknown. Please pick from the following:");
                                            for (PotionType pt : PotionType.values()) {
                                                plugin.getLogger().severe(pt.name());
                                            }
                                            match = false;
                                        }
                                    } else {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: potionType = null");
                                        match = false;
                                    }
                                    // Level check (upgraded)
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: level check " + part[2]);
                                    if (!part[2].isEmpty()) {
                                        // There is a level declared - check it
                                        if (StringUtils.isNumeric(part[2])) {
                                            int level = Integer.valueOf(part[2]);
                                            if (level != potion.getLevel()) {
                                                if (DEBUG)
                                                    plugin.getLogger().info("DEBUG: level does not match");
                                                match = false;
                                            }
                                        }
                                    }
                                    // Extended check
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: extended check " + part[3]);
                                    if (!part[3].isEmpty()) {
                                        if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: extended does not match");
                                        }
                                        if (part[3].equalsIgnoreCase("NOTEXTENDED") && potion.hasExtendedDuration()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: extended does not match");
                                        }
                                    }
                                    // Splash check
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                                    if (!part[4].isEmpty()) {
                                        if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: not splash");
                                        }
                                        if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: not no splash");
                                        }
                                    }
                                    // Quantity check
                                    if (match) {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: potion matches!");
                                        ItemStack removeItem = i.clone();
                                        if (removeItem.getAmount() > reqAmount) {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                            removeItem.setAmount(reqAmount);
                                        }
                                        count = count - removeItem.getAmount();
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: " + count + " left");
                                        toBeRemoved.add(removeItem);
                                    }
                                }
                            } else {
                                // V1.9 and above
                                PotionMeta potionMeta = (PotionMeta) i.getItemMeta();
                                // If any of the settings above are missing, then any is okay
                                boolean match = true;
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: name check " + part[1]);
                                // Name check
                                if (!part[1].isEmpty()) {
                                    // There is a name
                                    if (PotionType.valueOf(part[1]) != null) {
                                        if (!potionMeta.getBasePotionData().getType().name().equalsIgnoreCase(part[1])) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name does not match");
                                        } else {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: name matches");
                                        }
                                    } else {
                                        plugin.getLogger().severe("Potion type is unknown. Please pick from the following:");
                                        for (PotionType pt : PotionType.values()) {
                                            plugin.getLogger().severe(pt.name());
                                        }
                                        match = false;
                                    }
                                }
                                // plugin.getLogger().info("DEBUG: level check " + part[2]);
                                if (!part[2].isEmpty()) {
                                    // There is a level declared - check it
                                    if (StringUtils.isNumeric(part[2])) {
                                        int level = Integer.valueOf(part[2]);
                                        if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) {
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                            match = false;
                                        }
                                        if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) {
                                            match = false;
                                            if (DEBUG)
                                                plugin.getLogger().info("DEBUG: level does not match");
                                        }
                                    }
                                }
                                // Extended check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: extended check " + part[3]);
                                if (!part[3].isEmpty()) {
                                    if (part[3].equalsIgnoreCase("EXTENDED") && !potionMeta.getBasePotionData().isExtended()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                    if (part[3].equalsIgnoreCase("NOTEXTENDED") && potionMeta.getBasePotionData().isExtended()) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: extended does not match");
                                    }
                                }
                                // Splash or Linger check
                                if (DEBUG)
                                    plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                                if (!part[4].isEmpty()) {
                                    if (part[4].equalsIgnoreCase("SPLASH") && !i.getType().equals(Material.SPLASH_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not splash");
                                    }
                                    if (part[4].equalsIgnoreCase("NOSPLASH") && i.getType().equals(Material.SPLASH_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no splash");
                                    }
                                    if (part[4].equalsIgnoreCase("LINGER") && !i.getType().equals(Material.LINGERING_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not linger");
                                    }
                                    if (part[4].equalsIgnoreCase("NOLINGER") && i.getType().equals(Material.LINGERING_POTION)) {
                                        match = false;
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: not no linger");
                                    }
                                }
                                // Quantity check
                                if (match) {
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: potion matches!");
                                    ItemStack removeItem = i.clone();
                                    if (removeItem.getAmount() > reqAmount) {
                                        if (DEBUG)
                                            plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                        removeItem.setAmount(reqAmount);
                                    }
                                    count = count - removeItem.getAmount();
                                    if (DEBUG)
                                        plugin.getLogger().info("DEBUG: " + count + " left");
                                    toBeRemoved.add(removeItem);
                                }
                            }
                        }
                        if (count <= 0) {
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: Player has enough");
                            break;
                        }
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: still need " + count + " to complete");
                    }
                    if (count > 0) {
                        if (DEBUG)
                            plugin.getLogger().info("DEBUG: Player does not have enough");
                        return false;
                    }
                } else {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    return false;
                }
            }
        }
        if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) {
            // int qty = 0;
            if (DEBUG)
                plugin.getLogger().info("DEBUG: Removing items");
            for (ItemStack i : toBeRemoved) {
                // qty += i.getAmount();
                if (DEBUG)
                    plugin.getLogger().info("DEBUG: Remove " + i.toString() + "::" + i.getDurability() + " x " + i.getAmount());
                HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i);
                if (!leftOver.isEmpty()) {
                    plugin.getLogger().warning("Exploit? Could not remove the following in challenge " + challenge + " for player " + player.getName() + ":");
                    for (ItemStack left : leftOver.values()) {
                        plugin.getLogger().info(left.toString());
                    }
                    return false;
                }
            }
            // Remove money
            if (moneyReq > 0D) {
                EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq);
                if (!er.transactionSuccess()) {
                    plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq) + " from " + player.getName() + " in challenge " + challenge);
                    plugin.getLogger().warning("Player's balance is " + VaultHelper.econ.format(VaultHelper.econ.getBalance(player)));
                }
            }
        // plugin.getLogger().info("DEBUG: total = " + qty);
        }
        return true;
    }
    if (type.equalsIgnoreCase("island")) {
        final HashMap<MaterialData, Integer> neededItem = new HashMap<MaterialData, Integer>();
        final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>();
        if (!reqList.isEmpty()) {
            for (int i = 0; i < reqList.split(" ").length; i++) {
                final String[] sPart = reqList.split(" ")[i].split(":");
                try {
                    // Find out if the needed item is a Material or an Entity
                    boolean isEntity = false;
                    for (EntityType entityType : EntityType.values()) {
                        if (entityType.toString().equalsIgnoreCase(sPart[0])) {
                            isEntity = true;
                            break;
                        }
                    }
                    if (isEntity) {
                        // plugin.getLogger().info("DEBUG: Item " + sPart[0].toUpperCase() + " is an entity");
                        EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase());
                        if (entityType != null) {
                            neededEntities.put(entityType, Integer.parseInt(sPart[1]));
                        // plugin.getLogger().info("DEBUG: Needed entity is " + Integer.parseInt(sPart[1]) + " x " + EntityType.valueOf(sPart[0].toUpperCase()).toString());
                        }
                    } else {
                        Material item;
                        if (StringUtils.isNumeric(sPart[0])) {
                            item = Material.getMaterial(Integer.parseInt(sPart[0]));
                        } else {
                            item = Material.getMaterial(sPart[0].toUpperCase());
                        }
                        if (item != null) {
                            // We have two cases : quantity only OR durability + quantity
                            final int quantity;
                            final byte durability;
                            if (sPart.length == 2) {
                                // Only a quantity is specified
                                quantity = Integer.parseInt(sPart[1]);
                                durability = 0;
                            } else {
                                quantity = Integer.parseInt(sPart[2]);
                                durability = Byte.parseByte(sPart[1]);
                            }
                            neededItem.put(new MaterialData(item, durability), quantity);
                        // plugin.getLogger().info("DEBUG: Needed item is " + Integer.parseInt(sPart[1]) + " x " + Material.getMaterial(sPart[0]).toString());
                        } else {
                            plugin.getLogger().warning("Problem parsing required item for challenge " + challenge + " in challenges.yml!");
                            return false;
                        }
                    }
                } catch (Exception intEx) {
                    plugin.getLogger().warning("Problem parsing required items for challenge " + challenge + " in challenges.yml - skipping");
                    return false;
                }
            }
        }
        // We now have two sets of required items or entities
        // Check the items first
        final Location l = player.getLocation();
        // if (!neededItem.isEmpty()) {
        final int px = l.getBlockX();
        final int py = l.getBlockY();
        final int pz = l.getBlockZ();
        // Get search radius - min is 10, max is 50
        int searchRadius = getChallengeConfig().getInt("challenges.challengeList." + challenge + ".searchRadius", 10);
        if (searchRadius < 10) {
            searchRadius = 10;
        } else if (searchRadius > 50) {
            searchRadius = 50;
        }
        for (int x = -searchRadius; x <= searchRadius; x++) {
            for (int y = -searchRadius; y <= searchRadius; y++) {
                for (int z = -searchRadius; z <= searchRadius; z++) {
                    final MaterialData b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getState().getData();
                    if (neededItem.containsKey(b)) {
                        if (neededItem.get(b) == 1) {
                            neededItem.remove(b);
                        } else {
                            // Reduce the require amount by 1
                            neededItem.put(b, neededItem.get(b) - 1);
                        }
                    }
                }
            }
        }
        // Check if all the needed items have been amassed
        if (!neededItem.isEmpty()) {
            // plugin.getLogger().info("DEBUG: Insufficient items around");
            for (MaterialData missing : neededItem.keySet()) {
                Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededItem.get(missing) + " x " + Util.prettifyText(missing.getItemType().toString()) + ":" + missing.getData());
            }
            return false;
        } else {
            // Check for needed entities
            for (Entity entity : player.getNearbyEntities(searchRadius, searchRadius, searchRadius)) {
                // entity.getType().toString());
                if (neededEntities.containsKey(entity.getType())) {
                    // plugin.getLogger().info("DEBUG: Entity in list");
                    if (neededEntities.get(entity.getType()) == 1) {
                        neededEntities.remove(entity.getType());
                    // plugin.getLogger().info("DEBUG: Entity qty satisfied");
                    } else {
                        neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1);
                    // plugin.getLogger().info("DEBUG: Entity qty reduced by 1");
                    }
                } else {
                // plugin.getLogger().info("DEBUG: Entity not in list");
                }
            }
            if (neededEntities.isEmpty()) {
                return true;
            } else {
                for (EntityType missing : neededEntities.keySet()) {
                    Util.sendMessage(player, ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString()));
                }
                return false;
            }
        }
    }
    return true;
}
Also used : Entity(org.bukkit.entity.Entity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) EconomyResponse(net.milkbowl.vault.economy.EconomyResponse) Potion(org.bukkit.potion.Potion) Material(org.bukkit.Material) PotionMeta(org.bukkit.inventory.meta.PotionMeta) NMSAbstraction(com.wasteofplastic.askyblock.nms.NMSAbstraction) IOException(java.io.IOException) EntityType(org.bukkit.entity.EntityType) PotionType(org.bukkit.potion.PotionType) MaterialData(org.bukkit.material.MaterialData) ItemStack(org.bukkit.inventory.ItemStack) Location(org.bukkit.Location)

Example 37 with EntityType

use of org.bukkit.entity.EntityType in project askyblock by tastybento.

the class IslandGuard method onSpawnerBlockPlace.

/**
 * Sets spawners to their type
 * @param e - event
 */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onSpawnerBlockPlace(final BlockPlaceEvent e) {
    if (DEBUG)
        plugin.getLogger().info("DEBUG: block place");
    if (inWorld(e.getPlayer()) && Util.playerIsHolding(e.getPlayer(), Material.MOB_SPAWNER)) {
        if (DEBUG)
            plugin.getLogger().info("DEBUG: in world");
        // Get item in hand
        for (ItemStack item : Util.getPlayerInHandItems(e.getPlayer())) {
            if (item.getType().equals(Material.MOB_SPAWNER) && item.hasItemMeta() && item.getItemMeta().hasLore()) {
                if (DEBUG)
                    plugin.getLogger().info("DEBUG: spawner in hand with lore");
                List<String> lore = item.getItemMeta().getLore();
                if (!lore.isEmpty()) {
                    if (DEBUG)
                        plugin.getLogger().info("DEBUG: lore is not empty");
                    for (EntityType type : EntityType.values()) {
                        if (lore.get(0).equals(Util.prettifyText(type.name()))) {
                            // Found the spawner type
                            if (DEBUG)
                                plugin.getLogger().info("DEBUG: found type");
                            e.getBlock().setType(Material.MOB_SPAWNER);
                            CreatureSpawner cs = (CreatureSpawner) e.getBlock().getState();
                            cs.setSpawnedType(type);
                        }
                    }
                // Spawner type not found - do anything : it may be another plugin's spawner
                }
            }
        }
    }
}
Also used : EntityType(org.bukkit.entity.EntityType) ItemStack(org.bukkit.inventory.ItemStack) CreatureSpawner(org.bukkit.block.CreatureSpawner) EventHandler(org.bukkit.event.EventHandler)

Example 38 with EntityType

use of org.bukkit.entity.EntityType in project askyblock by tastybento.

the class IslandGuard method onExplosion.

@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onExplosion(final EntityExplodeEvent e) {
    if (DEBUG) {
    // Commented out due to Ender dragon spam in Paper Spigot
    // plugin.getLogger().info(e.getEventName());
    // plugin.getLogger().info("Entity exploding is " + e.getEntity());
    }
    if (!inWorld(e.getLocation())) {
        return;
    }
    // Find out what is exploding
    Entity expl = e.getEntity();
    if (expl == null) {
        // Note player can still die from beds exploding in the nether.
        if (!Settings.allowTNTDamage) {
            // plugin.getLogger().info("TNT block damage prevented");
            e.blockList().clear();
        } else {
            if (!Settings.allowChestDamage) {
                List<Block> toberemoved = new ArrayList<Block>();
                // Save the chest blocks in a list
                for (Block b : e.blockList()) {
                    switch(b.getType()) {
                        case CHEST:
                        case ENDER_CHEST:
                        case STORAGE_MINECART:
                        case TRAPPED_CHEST:
                            toberemoved.add(b);
                            break;
                        default:
                            break;
                    }
                }
                // Now delete them
                for (Block b : toberemoved) {
                    e.blockList().remove(b);
                }
            }
        }
        return;
    }
    // prevent at spawn
    if (plugin.getGrid().isAtSpawn(e.getLocation())) {
        e.setCancelled(true);
    }
    // Find out what is exploding
    EntityType exploding = e.getEntityType();
    if (exploding == null) {
        return;
    }
    switch(exploding) {
        case CREEPER:
            if (!Settings.allowCreeperDamage) {
                // plugin.getLogger().info("Creeper block damage prevented");
                e.blockList().clear();
            } else {
                // Check if creeper griefing is allowed
                if (!Settings.allowCreeperGriefing) {
                    // Find out who the creeper was targeting
                    Creeper creeper = (Creeper) e.getEntity();
                    if (creeper.getTarget() instanceof Player) {
                        Player target = (Player) creeper.getTarget();
                        // Check if the target is on their own island or not
                        if (!plugin.getGrid().locationIsOnIsland(target, e.getLocation())) {
                            // They are a visitor tsk tsk
                            // Stop the blocks from being damaged, but allow hurt still
                            e.blockList().clear();
                        }
                    }
                    // Check if this creeper was lit by a visitor
                    if (litCreeper.contains(creeper.getUniqueId())) {
                        if (DEBUG) {
                            plugin.getLogger().info("DBEUG: preventing creeper from damaging");
                        }
                        litCreeper.remove(creeper.getUniqueId());
                        e.setCancelled(true);
                        return;
                    }
                }
                if (!Settings.allowChestDamage) {
                    List<Block> toberemoved = new ArrayList<Block>();
                    // Save the chest blocks in a list
                    for (Block b : e.blockList()) {
                        switch(b.getType()) {
                            case CHEST:
                            case ENDER_CHEST:
                            case STORAGE_MINECART:
                            case TRAPPED_CHEST:
                                toberemoved.add(b);
                                break;
                            default:
                                break;
                        }
                    }
                    // Now delete them
                    for (Block b : toberemoved) {
                        e.blockList().remove(b);
                    }
                }
            }
            break;
        case PRIMED_TNT:
        case MINECART_TNT:
            if (!Settings.allowTNTDamage) {
                // plugin.getLogger().info("TNT block damage prevented");
                e.blockList().clear();
            } else {
                if (!Settings.allowChestDamage) {
                    List<Block> toberemoved = new ArrayList<Block>();
                    // Save the chest blocks in a list
                    for (Block b : e.blockList()) {
                        switch(b.getType()) {
                            case CHEST:
                            case ENDER_CHEST:
                            case STORAGE_MINECART:
                            case TRAPPED_CHEST:
                                toberemoved.add(b);
                                break;
                            default:
                                break;
                        }
                    }
                    // Now delete them
                    for (Block b : toberemoved) {
                        e.blockList().remove(b);
                    }
                }
            }
            break;
        default:
            break;
    }
}
Also used : EntityType(org.bukkit.entity.EntityType) Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) Player(org.bukkit.entity.Player) Creeper(org.bukkit.entity.Creeper) ArrayList(java.util.ArrayList) Block(org.bukkit.block.Block) ASkyBlock(com.wasteofplastic.askyblock.ASkyBlock) EventHandler(org.bukkit.event.EventHandler)

Example 39 with EntityType

use of org.bukkit.entity.EntityType in project Statz by Staartvin.

the class ImportManager method importFromStats3.

/**
 * Import data from Stats 3.
 *
 * @return number of entries imported from Stats 3.
 */
@SuppressWarnings("deprecation")
public int importFromStats3() {
    int importedEntries = 0;
    LibraryHook hook = plugin.getDependencyManager().getLibraryHook(Library.STATS);
    if (hook == null || !hook.isAvailable()) {
        plugin.getLogger().warning("Cannot import data from Stats 3 as it is not running!");
        return -1;
    }
    int waitingTime = 10;
    StatsHook stats3 = (StatsHook) hook;
    List<UUID> loggedPlayers = stats3.getLoggedPlayers();
    plugin.getLogsManager().writeToLogFile("Requested " + loggedPlayers.size() + " users from Stats. Now waiting " + "" + ((loggedPlayers.size() * waitingTime) / 1000.0) + " seconds for the response...");
    plugin.getLogger().info("Requested all users for importing, now wait " + ((loggedPlayers.size() * waitingTime) / 1000.0) + " seconds for Stats to load all users.");
    try {
        Thread.sleep(loggedPlayers.size() * waitingTime);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    plugin.getLogsManager().writeToLogFile("Started processing UUIDs of Stats.");
    for (UUID uuid : loggedPlayers) {
        StatsHolder user = stats3.getStatsHolder(uuid);
        importedEntries++;
        if (importedEntries % 1000 == 0) {
            plugin.getLogsManager().writeToLogFile("Processed " + importedEntries + " / " + loggedPlayers.size() + " uuids.");
        }
        Collection<Stat> storedStats = user.getStats();
        for (Stat stat : storedStats) {
            for (StatEntry entry : user.getStats(stat)) {
                Map<String, Object> metadata = entry.getMetadata();
                double value = entry.getValue();
                String worldName = (String) metadata.get("world");
                if (stat instanceof Move) {
                    // Movement stat
                    double moveType = Double.parseDouble(metadata.get("type").toString());
                    String movementType = "WALK";
                    switch((int) moveType) {
                        case 0:
                            movementType = "WALK";
                            break;
                        case 1:
                            movementType = "BOAT";
                            break;
                        case 2:
                            movementType = "MINECART";
                            break;
                        case 3:
                            movementType = "PIG";
                            break;
                        case 4:
                            movementType = "PIG IN MINECART";
                            break;
                        case 5:
                            movementType = "HORSE";
                            break;
                        case 6:
                            movementType = "FLY";
                            break;
                    }
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.DISTANCE_TRAVELLED, StatzUtil.makeQuery("value", (value), "moveType", movementType, "world", worldName));
                } else if (stat instanceof Kill) {
                    // Kill stat
                    EntityType entity = EntityType.fromName((String) metadata.get("entityType"));
                    String entityName = entity != null ? entity.toString() : "UNKNOWN";
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.KILLS_MOBS, StatzUtil.makeQuery("value", (value), "mob", entityName, "world", worldName, "weapon", "UNKNOWN"));
                } else if (stat instanceof Teleports) {
                    // Teleport stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.TELEPORTS, StatzUtil.makeQuery("value", (value), "world", "UNKNOWN", "destWorld", worldName, "cause", "UNKNOWN"));
                } else if (stat instanceof Arrows) {
                    // Arrows shot stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ARROWS_SHOT, StatzUtil.makeQuery("value", (value), "world", worldName, "forceShot", 1));
                } else if (stat instanceof BedEnter) {
                    // Beds entered stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ENTERED_BEDS, StatzUtil.makeQuery("value", (value), "world", worldName));
                } else if (stat instanceof BlockBreak) {
                    // Blocks broken stat
                    int dataValue = Integer.parseInt(metadata.get("data").toString());
                    String blockName = (String) metadata.get("name");
                    Material material = Material.getMaterial(blockName);
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.BLOCKS_BROKEN, StatzUtil.makeQuery("value", (value), "world", worldName, "datavalue", dataValue, "typeid", material.getId()));
                } else if (stat instanceof BlockPlace) {
                    // Blocks placed stat
                    int dataValue = Integer.parseInt(metadata.get("data").toString());
                    String blockName = (String) metadata.get("name");
                    Material material = Material.getMaterial(blockName);
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.BLOCKS_PLACED, StatzUtil.makeQuery("value", (value), "world", worldName, "datavalue", dataValue, "typeid", material.getId()));
                } else if (stat instanceof BucketEmpty) {
                    // Buckets emptied stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.BUCKETS_EMPTIED, StatzUtil.makeQuery("value", (value), "world", worldName));
                } else if (stat instanceof BucketFill) {
                    // Buckets filled stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.BUCKETS_FILLED, StatzUtil.makeQuery("value", (value), "world", worldName));
                } else if (stat instanceof CommandsDone) {
                    // Commands performed stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.COMMANDS_PERFORMED, StatzUtil.makeQuery("value", (value), "world", worldName, "command", "UNKNOWN", "arguments", "UNKNOWN"));
                } else if (stat instanceof DamageTaken) {
                    // Damage taken stat
                    String cause = metadata == null ? "UNKNOWN" : (metadata.get("cause") != null ? metadata.get("cause").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.DAMAGE_TAKEN, StatzUtil.makeQuery("value", (value), "world", worldName, "cause", cause));
                } else if (stat instanceof Death) {
                    // Times died stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.DEATHS, StatzUtil.makeQuery("value", (value), "world", worldName));
                } else if (stat instanceof EggsThrown) {
                    // Eggs thrown stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.EGGS_THROWN, StatzUtil.makeQuery("value", (value), "world", worldName));
                } else if (stat instanceof FishCaught) {
                    // Fish caught stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ITEMS_CAUGHT, StatzUtil.makeQuery("value", (value), "world", worldName, "caught", "UNKNOWN"));
                } else if (stat instanceof ItemsCrafted) {
                    // Items crafted stat
                    String name = metadata == null ? "UNKNOWN" : (metadata.get("name") != null ? metadata.get("name").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ITEMS_CRAFTED, StatzUtil.makeQuery("value", (value), "world", worldName, "item", name));
                } else if (stat instanceof ItemsDropped) {
                    // Items dropped stat
                    String name = metadata == null ? "UNKNOWN" : (metadata.get("name") != null ? metadata.get("name").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ITEMS_DROPPED, StatzUtil.makeQuery("value", (value), "world", worldName, "item", name));
                } else if (stat instanceof ItemsPickedUp) {
                    // Items picked up stat
                    String name = metadata == null ? "UNKNOWN" : (metadata.get("name") != null ? metadata.get("name").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ITEMS_PICKED_UP, StatzUtil.makeQuery("value", (value), "world", worldName, "item", name));
                } else if (stat instanceof ItemsDropped) {
                    // Items dropped stat
                    String name = metadata == null ? "UNKNOWN" : (metadata.get("name") != null ? metadata.get("name").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.ITEMS_DROPPED, StatzUtil.makeQuery("value", (value), "world", worldName, "item", name));
                } else if (stat instanceof Joins) {
                    // Times joined stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.JOINS, StatzUtil.makeQuery("value", (value)));
                } else if (stat instanceof Omnomnom) {
                    // Food eaten stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.FOOD_EATEN, StatzUtil.makeQuery("value", (value), "world", worldName, "foodEaten", "UNKNOWN"));
                } else if (stat instanceof Playtime) {
                    // Time played stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.TIME_PLAYED, StatzUtil.makeQuery("value", (value / 60d), "world", worldName));
                } else if (stat instanceof PVP) {
                    // Number of players killed stat
                    String victim = metadata == null ? "UNKNOWN" : (metadata.get("victim") != null ? metadata.get("victim").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.KILLS_PLAYERS, StatzUtil.makeQuery("value", (value), "world", worldName, "playerKilled", victim));
                } else if (stat instanceof Shears) {
                    // Number of sheep shorn stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.TIMES_SHORN, StatzUtil.makeQuery("value", (value), "world", worldName));
                } else if (stat instanceof WorldChanged) {
                    // Times changed of worlds stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.WORLDS_CHANGED, StatzUtil.makeQuery("value", (value), "world", "UNKNOWN", "destWorld", "UNKNOWN"));
                } else if (stat instanceof TimesKicked) {
                    // Times kicked stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.TIMES_KICKED, StatzUtil.makeQuery("value", (value), "world", worldName, "reason", "UNKNOWN"));
                } else if (stat instanceof ToolsBroken) {
                    // Tools broken stat
                    String name = metadata == null ? "UNKNOWN" : (metadata.get("name") != null ? metadata.get("name").toString() : "UNKNOWN");
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.TOOLS_BROKEN, StatzUtil.makeQuery("value", (value), "world", worldName, "item", name));
                } else if (stat instanceof Trades) {
                    // Number of trades made stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.VILLAGER_TRADES, StatzUtil.makeQuery("value", (value), "world", worldName, "trade", "UNKNOWN"));
                } else if (stat instanceof XpGained) {
                    // XP gained stat
                    plugin.getDataManager().setPlayerInfo(uuid, PlayerStat.XP_GAINED, StatzUtil.makeQuery("value", (value), "world", worldName));
                }
            }
        }
    }
    return importedEntries;
}
Also used : LibraryHook(me.staartvin.plugins.pluginlibrary.hooks.LibraryHook) PlayerStat(me.staartvin.statz.datamanager.player.PlayerStat) Stat(nl.lolmewn.stats.api.stat.Stat) UUID(java.util.UUID) StatsHook(me.staartvin.plugins.pluginlibrary.hooks.StatsHook) Material(org.bukkit.Material) StatsHolder(nl.lolmewn.stats.api.user.StatsHolder) EntityType(org.bukkit.entity.EntityType) StatEntry(nl.lolmewn.stats.api.stat.StatEntry)

Example 40 with EntityType

use of org.bukkit.entity.EntityType in project LandLord by SpatiumPrinceps.

the class AbstractManage method create.

@Override
protected void create() {
    List<String> regenerateDesc = lm.getStringList("Commands.Manage.Regenerate.description");
    List<String> greetDesc = lm.getStringList("Commands.Manage.SetGreet.description");
    List<String> farewellDesc = lm.getStringList("Commands.Manage.SetFarewell.description");
    int position = 0;
    if (regions.size() < 1)
        return;
    OwnedLand land = regions.get(0);
    for (LLFlag iFlag : land.getFlags()) {
        // For every IFlag of the land we wanna display an icon in the gui IF the flag is enabled for change
        String flagName = iFlag.getWGFlag().getName();
        String title = lm.getRawString("Commands.Manage.Allow" + flagName.substring(0, 1).toUpperCase() + flagName.substring(1) + ".title");
        List<String> description = lm.getStringList("Commands.Manage.Allow" + flagName.substring(0, 1).toUpperCase() + flagName.substring(1) + ".description");
        if (plugin.getConfig().getBoolean("Manage." + flagName + ".enable")) {
            int finalPosition = position;
            this.setIcon(position, new Icon(createItem(iFlag.getMaterial(), 1, title, formatList(description, iFlag.getStatus()))).addClickAction((p, icon) -> {
                for (OwnedLand region : regions) {
                    for (LLFlag llFlag : region.getFlags()) {
                        if (llFlag.getWGFlag().equals(iFlag.getWGFlag())) {
                            llFlag.toggle();
                        }
                    }
                }
                updateLore(finalPosition, formatList(description, iFlag.getStatus()));
            }));
            position++;
        }
    }
    // Reminder: Regenerate is not implemented in Manageall, cos it might cos some trouble. Calculating costs might be a bit tedious
    if (plugin.getConfig().getBoolean("Manage.regenerate.enable") && regions.size() == 1) {
        double cost = plugin.getConfig().getDouble("ResetCost");
        this.setIcon(position, new Icon(createItem(Material.BARRIER, 1, lm.getRawString("Commands.Manage.Regenerate.title"), formatList(regenerateDesc, (Options.isVaultEnabled() ? plugin.getVaultHandler().format(cost) : "-1")))).addClickAction((p, ic) -> {
            if (land.isOwner(player.getUniqueId())) {
                ConfirmationGUI confi = new ConfirmationGUI(p, lm.getRawString("Commands.Manage.Regenerate.confirmation").replace("%cost%", (Options.isVaultEnabled() ? plugin.getVaultHandler().format(cost) : "-1")), (p1, ic1) -> {
                    boolean flag = false;
                    if (Options.isVaultEnabled())
                        if (plugin.getVaultHandler().hasBalance(player.getUniqueId(), cost)) {
                            plugin.getVaultHandler().take(player.getUniqueId(), cost);
                            flag = true;
                        } else
                            player.sendMessage(lm.getString("Commands.Manage.Regenerate.notEnoughMoney").replace("%cost%", plugin.getVaultHandler().format(cost)).replace("%name%", land.getName()));
                    else
                        flag = true;
                    if (flag) {
                        if (land.isOwner(player.getUniqueId())) {
                            player.getWorld().regenerateChunk(land.getChunk().getX(), land.getChunk().getZ());
                            player.sendMessage(lm.getString("Commands.Manage.Regenerate.success").replace("%land%", land.getName()));
                            display();
                        }
                    }
                }, (p2, ic2) -> {
                    player.sendMessage(lm.getString("Commands.Manage.Regenerate.abort").replace("%land%", land.getName()));
                    display();
                }, this);
                confi.setConfirm(lm.getRawString("Confirmation.accept"));
                confi.setDecline(lm.getRawString("Confirmation.decline"));
                confi.display();
            }
        }));
        position++;
    }
    // Set greet icon
    if (plugin.getConfig().getBoolean("Manage.setgreet.enable")) {
        String currentGreet = land.getWGLand().getFlag(DefaultFlag.GREET_MESSAGE);
        this.setIcon(position, new Icon(createItem(Material.valueOf(plugin.getConfig().getString("Manage.setgreet.item")), 1, lm.getRawString("Commands.Manage.SetGreet.title"), formatList(greetDesc, currentGreet))).addClickAction(((p, ic) -> {
            p.closeInventory();
            ComponentBuilder builder = new ComponentBuilder(lm.getString("Commands.Manage.SetGreet.clickMsg"));
            if (regions.size() > 1)
                builder.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/land manage setgreetall "));
            else
                builder.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/land manage setgreet "));
            p.spigot().sendMessage(builder.create());
        })));
        position++;
    }
    // TODO add functionality for manageall
    if (plugin.getConfig().getBoolean("Manage.mob-spawning.enable")) {
        String title = lm.getRawString("Commands.Manage.AllowMob-spawning.title");
        this.setIcon(position, new Icon(createItem(Material.valueOf(plugin.getConfig().getString("Manage.mob-spawning.item")), 1, title, lm.getStringList("Commands.Manage.AllowMob-spawning.description"))).addClickAction((p, icon) -> {
            // Open a new gui with spawneggs where you can manage the spawns by clicking on them
            List<Icon> icons = new ArrayList<>();
            EntityType[] types = EntityType.values();
            List<String> lore = lm.getStringList("Commands.Manage.AllowMob-spawning.toggleItem.description");
            MultiPagedGUI gui = new MultiPagedGUI(p, 4, title, icons, this) {
            };
            for (EntityType t : types) {
                if (t.isAlive() && t.isSpawnable()) {
                    if (!toggleMobs.contains(t.name()))
                        continue;
                    ItemStack spawnEgg = new ItemStack(Material.MONSTER_EGG);
                    SpawnEggMeta meta = (SpawnEggMeta) spawnEgg.getItemMeta();
                    meta.setSpawnedType(t);
                    meta.setDisplayName(lm.getRawString("Commands.Manage.AllowMob-spawning.toggleItem.title").replace("%mob%", t.name()));
                    Set<EntityType> flag = land.getWGLand().getFlag(DefaultFlag.DENY_SPAWN);
                    String state;
                    if (flag != null)
                        state = (flag.contains(t) ? "DENY" : "ALLOW");
                    else
                        state = "ALLOW";
                    List<String> formattedLore = new ArrayList<>();
                    for (String s : lore) {
                        formattedLore.add(s.replace("%mob%", t.name()).replace("%value%", state));
                    }
                    meta.setLore(formattedLore);
                    spawnEgg.setItemMeta(meta);
                    Icon ic = new Icon(spawnEgg).addClickAction((clickingPlayer, ic3) -> {
                        for (OwnedLand region : regions) {
                            Set<EntityType> localFlag = region.getWGLand().getFlag(DefaultFlag.DENY_SPAWN);
                            // Toggle spawning of specific mob
                            if (localFlag != null) {
                                if (localFlag.contains(t))
                                    localFlag.remove(t);
                                else
                                    localFlag.add(t);
                            } else {
                                Set<EntityType> set = new HashSet<>();
                                set.add(t);
                                region.getWGLand().setFlag(DefaultFlag.DENY_SPAWN, set);
                            }
                        }
                        // update icon text
                        String iconState;
                        if (flag != null)
                            iconState = (flag.contains(t) ? "DENY" : "ALLOW");
                        else
                            iconState = "ALLOW";
                        List<String> newLore = new ArrayList<>();
                        for (String s : lore) {
                            newLore.add(s.replace("%mob%", t.name()).replace("%value%", iconState));
                        }
                        // System.out.println(newLore + " :" + finalIconPos);
                        ic3.setLore(newLore);
                        gui.refresh();
                    });
                    icons.add(ic);
                }
            }
            gui.display();
        }));
        position++;
    }
    // set farewell icon
    if (plugin.getConfig().getBoolean("Manage.setfarewell.enable")) {
        String currentFarewell = land.getWGLand().getFlag(DefaultFlag.FAREWELL_MESSAGE);
        this.setIcon(position, new Icon(createItem(Material.valueOf(plugin.getConfig().getString("Manage.setfarewell.item")), 1, lm.getRawString("Commands.Manage.SetFarewell.title"), formatList(farewellDesc, currentFarewell))).addClickAction(((p, icon) -> {
            p.closeInventory();
            ComponentBuilder builder = new ComponentBuilder(lm.getString("Commands.Manage.SetFarewell.clickMsg"));
            if (regions.size() > 1)
                builder.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/land manage setfarewellall "));
            else
                builder.event(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/land manage setfarewell "));
            p.spigot().sendMessage(builder.create());
        })));
        position++;
    }
    // set friends icon
    if (plugin.getConfig().getBoolean("Manage.friends.enable")) {
        ItemStack skull = createSkull(player.getName(), lm.getRawString("Commands.Manage.ManageFriends.title"), lm.getStringList("Commands.Manage.ManageFriends.description"));
        Set<UUID> friends = land.getWGLand().getMembers().getUniqueIds();
        MultiPagedGUI friendsGui = new MultiPagedGUI(player, (int) Math.ceil((double) friends.size() / 9.0), lm.getRawString("Commands.Manage.ManageFriends.title"), new ArrayList<>(), this) {
        };
        friends.forEach(id -> friendsGui.addIcon(new Icon(createSkull(Bukkit.getOfflinePlayer(id).getName(), Bukkit.getOfflinePlayer(id).getName(), formatFriendsSegment(id))).addClickAction((player, icon) -> {
            ConfirmationGUI confirmationGUI = new ConfirmationGUI(player, lm.getRawString("Commands.Manage.ManageFriends.unfriend").replace("%player%", Bukkit.getOfflinePlayer(id).getName()), (p, ic1) -> {
                friendsGui.removeIcon(friendsGui.filter(Bukkit.getOfflinePlayer(id).getName()).get(0));
                if (regions.size() > 1)
                    Bukkit.dispatchCommand(player, "land unfriendall " + Bukkit.getOfflinePlayer(id).getName());
                else
                    Bukkit.dispatchCommand(player, "land unfriend " + Bukkit.getOfflinePlayer(id).getName());
                player.closeInventory();
                friendsGui.display();
            }, (p, ic2) -> {
                player.closeInventory();
                friendsGui.display();
            }, friendsGui);
            confirmationGUI.setConfirm(lm.getRawString("Confirmation.accept"));
            confirmationGUI.setDecline(lm.getRawString("Confirmation.decline"));
            confirmationGUI.display();
        })));
        this.setIcon(position, new Icon(skull).setName(lm.getRawString("Commands.Manage.ManageFriends.title")).addClickAction((p, ic) -> friendsGui.display()));
        position++;
    }
    if (plugin.getConfig().getBoolean("Manage.unclaim.enable")) {
        this.setIcon(position, new Icon(createItem(Material.valueOf(plugin.getConfig().getString("Manage.unclaim.item")), 1, lm.getRawString("Commands.Manage.Unclaim.title"), lm.getStringList("Commands.Manage.Unclaim.description"))).addClickAction(((player1, icon) -> {
            ConfirmationGUI gui = new ConfirmationGUI(player1, lm.getRawString("Commands.Manage.Unclaim.confirmationTitle").replace("%land%", land.getName()), (p, ic2) -> {
                if (regions.size() > 1)
                    Bukkit.dispatchCommand(p, "ll unclaimall");
                else
                    Bukkit.dispatchCommand(p, "ll unclaim " + land.getName());
                p.closeInventory();
            }, (p, ic) -> {
                p.closeInventory();
                display();
            }, this);
            gui.setConfirm(lm.getRawString("Confirmation.accept"));
            gui.setDecline(lm.getRawString("Confirmation.decline"));
            gui.display();
        })));
        position++;
    }
}
Also used : MultiPagedGUI(biz.princeps.lib.gui.MultiPagedGUI) java.util(java.util) ItemMeta(org.bukkit.inventory.meta.ItemMeta) ClickEvent(net.md_5.bungee.api.chat.ClickEvent) LLFlag(biz.princeps.landlord.flags.LLFlag) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) Landlord(biz.princeps.landlord.Landlord) OwnedLand(biz.princeps.landlord.util.OwnedLand) CompletableFuture(java.util.concurrent.CompletableFuture) Player(org.bukkit.entity.Player) SkullMeta(org.bukkit.inventory.meta.SkullMeta) DefaultFlag(com.sk89q.worldguard.protection.flags.DefaultFlag) ComponentBuilder(net.md_5.bungee.api.chat.ComponentBuilder) Conditions(biz.princeps.lib.storage.requests.Conditions) SpawnEggMeta(org.bukkit.inventory.meta.SpawnEggMeta) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) ConfirmationGUI(biz.princeps.lib.gui.ConfirmationGUI) LPlayer(biz.princeps.landlord.persistent.LPlayer) Options(biz.princeps.landlord.api.Options) EntityType(org.bukkit.entity.EntityType) OfflinePlayer(org.bukkit.OfflinePlayer) ItemStack(org.bukkit.inventory.ItemStack) ExecutionException(java.util.concurrent.ExecutionException) AbstractGUI(biz.princeps.lib.gui.simple.AbstractGUI) LangManager(biz.princeps.landlord.manager.LangManager) Icon(biz.princeps.lib.gui.simple.Icon) SpawnEggMeta(org.bukkit.inventory.meta.SpawnEggMeta) OwnedLand(biz.princeps.landlord.util.OwnedLand) ClickEvent(net.md_5.bungee.api.chat.ClickEvent) LLFlag(biz.princeps.landlord.flags.LLFlag) EntityType(org.bukkit.entity.EntityType) MultiPagedGUI(biz.princeps.lib.gui.MultiPagedGUI) ConfirmationGUI(biz.princeps.lib.gui.ConfirmationGUI) Icon(biz.princeps.lib.gui.simple.Icon) ItemStack(org.bukkit.inventory.ItemStack) ComponentBuilder(net.md_5.bungee.api.chat.ComponentBuilder)

Aggregations

EntityType (org.bukkit.entity.EntityType)109 ArrayList (java.util.ArrayList)29 ItemStack (org.bukkit.inventory.ItemStack)28 Material (org.bukkit.Material)23 Player (org.bukkit.entity.Player)23 Entity (org.bukkit.entity.Entity)19 Location (org.bukkit.Location)17 IOException (java.io.IOException)16 File (java.io.File)13 LivingEntity (org.bukkit.entity.LivingEntity)13 EventHandler (org.bukkit.event.EventHandler)12 PotionType (org.bukkit.potion.PotionType)12 HashMap (java.util.HashMap)10 ConfigurationSection (org.bukkit.configuration.ConfigurationSection)9 Block (org.bukkit.block.Block)8 YamlConfiguration (org.bukkit.configuration.file.YamlConfiguration)8 World (org.bukkit.World)7 SpawnEgg (org.bukkit.material.SpawnEgg)7 UUID (java.util.UUID)5 Biome (org.bukkit.block.Biome)5