Search in sources :

Example 1 with JavascriptEngine

use of com.bencodez.advancedcore.api.javascript.JavascriptEngine in project AdvancedCore by BenCodez.

the class RewardHandler method loadInjectedRewards.

public void loadInjectedRewards() {
    injectedRewards.add(new RewardInjectDouble("Money", 0) {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, double num, HashMap<String, String> placeholders) {
            user.giveMoney(num);
            return "" + (int) num;
        }
    }.asPlaceholder("Money").priority(100).addEditButton(new EditGUIButton(new ItemBuilder(Material.DIAMOND), new EditGUIValueInventory("Money") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditMoney() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Money to execute, may not work on some economy plugins").addLore("Supports random amounts"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getDouble(inject.getPath(), -1) == 0) {
                warning(reward, inject, "Money can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectConfigurationSection("Money") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            double minMoney = section.getDouble("Min", 0);
            double maxMoney = section.getDouble("Max", 0);
            double value = ThreadLocalRandom.current().nextDouble(minMoney, maxMoney);
            user.giveMoney(value);
            DecimalFormat f = new DecimalFormat("##.00");
            return "" + f.format(value);
        }
    }.asPlaceholder("Money").priority(100).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getDouble("Money.Max", -1) == 0) {
                warning(reward, inject, "Maxium money can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectInt("EXP", 0) {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, int num, HashMap<String, String> placeholders) {
            user.giveExp(num);
            return null;
        }
    }.asPlaceholder("EXP").priority(100).addEditButton(new EditGUIButton(new ItemBuilder("EXPERIENCE_BOTTLE"), new EditGUIValueInventory("EXP") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditEXP() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("EXP to give"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getDouble(inject.getPath(), -1) == 0) {
                warning(reward, inject, "EXP can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectInt("EXPLevels", 0) {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, int num, HashMap<String, String> placeholders) {
            user.giveExpLevels(num);
            return null;
        }
    }.asPlaceholder("EXP").priority(100).addEditButton(new EditGUIButton(new ItemBuilder("EXPERIENCE_BOTTLE"), new EditGUIValueInventory("EXPLevels") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditEXPLevels() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("EXPLevels to give"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getDouble(inject.getPath(), -1) == 0) {
                warning(reward, inject, "EXP can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectConfigurationSection("EXP") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            int minEXP = section.getInt("Min", 0);
            int maxEXP = section.getInt("Max", 0);
            int value = ThreadLocalRandom.current().nextInt(minEXP, maxEXP);
            user.giveExp(value);
            return "" + value;
        }
    }.asPlaceholder("EXP").priority(100).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getDouble("EXP.Max", -1) == 0) {
                warning(reward, inject, "Max EXP can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectConfigurationSection("EXPLevels") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            int minEXP = section.getInt("Min", 0);
            int maxEXP = section.getInt("Max", 0);
            int value = ThreadLocalRandom.current().nextInt(minEXP, maxEXP);
            user.giveExpLevels(value);
            return "" + value;
        }
    }.asPlaceholder("EXP").priority(100).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getDouble("EXP.Max", -1) == 0) {
                warning(reward, inject, "Max EXP can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectString("Message") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, String value, HashMap<String, String> placeholders) {
            user.sendMessage(value, placeholders);
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder("OAK_SIGN"), new EditGUIValueInventory("Messages") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditMessages() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addCheckKey("Message"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getString(inject.getPath()).isEmpty()) {
                warning(reward, inject, "No player message set");
            }
        }
    }));
    injectedRewards.add(new RewardInjectStringList("Messages.Player") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, ArrayList<String> value, HashMap<String, String> placeholders) {
            user.sendMessage(value, placeholders);
            return null;
        }
    });
    injectedRewards.add(new RewardInjectStringList("Message") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, ArrayList<String> value, HashMap<String, String> placeholders) {
            user.sendMessage(value, placeholders);
            return null;
        }
    });
    injectedRewards.add(new RewardInjectString("Messages.Player") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, String value, HashMap<String, String> placeholders) {
            user.sendMessage(value, placeholders);
            return null;
        }
    }.validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.isString(inject.getPath()) && data.getString(inject.getPath()).isEmpty()) {
                warning(reward, inject, "No player message set");
            }
        }
    }));
    injectedRewards.add(new RewardInjectStringList("Messages.Broadcast") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, ArrayList<String> value, HashMap<String, String> placeholders) {
            String playerName = user.getPlayerName();
            if (plugin.getOptions().getBroadcastBlacklist().contains(playerName)) {
                debug("Not broadcasting for " + playerName + ", in blacklist");
                return null;
            }
            for (String str : value) {
                MiscUtils.getInstance().broadcast(StringParser.getInstance().replacePlaceHolders(user.getPlayer(), StringParser.getInstance().replacePlaceHolder(str, placeholders)));
            }
            return null;
        }
    }.validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
        }
    }));
    injectedRewards.add(new RewardInjectString("Messages.Broadcast") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, String value, HashMap<String, String> placeholders) {
            String playerName = user.getPlayerName();
            if (plugin.getOptions().getBroadcastBlacklist().contains(playerName)) {
                debug("Not broadcasting for " + playerName + ", in blacklist");
                return null;
            }
            MiscUtils.getInstance().broadcast(StringParser.getInstance().replacePlaceHolders(user.getPlayer(), StringParser.getInstance().replacePlaceHolder(value, placeholders)));
            return null;
        }
    }.validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (!data.isList(inject.getPath())) {
                if (data.getString(inject.getPath(), "Empty").isEmpty()) {
                    warning(reward, inject, "No broadcast was set");
                }
            }
        }
    }));
    injectedRewards.add(new RewardInjectString("Command") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, String value, HashMap<String, String> placeholders) {
            MiscUtils.getInstance().executeConsoleCommands(user.getPlayer(), value, placeholders);
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder("COMMAND_BLOCK"), new EditGUIValueString("Command", null) {

        @Override
        public void setValue(Player player, String value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Execute single console command"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getString(inject.getPath()).startsWith("/")) {
                warning(reward, inject, "Can't start command with /");
            }
        }
    }));
    injectedRewards.add(new RewardInjectConfigurationSection("ActionBar") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            user.sendActionBar(StringParser.getInstance().replacePlaceHolder(section.getString("Message", ""), placeholders), section.getInt("Delay", 30));
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("ActionBar") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditActionBar() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Actionbar configuration"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            String str = data.getString("ActionBar.Message");
            int delay = data.getInt("ActionBar.Delay", -1);
            if (str != null && str.isEmpty()) {
                warning(reward, inject, "No actionbar message set");
            }
            if (delay == -1) {
                warning(reward, inject, "No actionbar delay set");
            } else if (delay == 0) {
                warning(reward, inject, "Actionbar delay can not be 0");
            }
        }
    }));
    injectedRewards.add(new RewardInjectStringList("Commands") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, ArrayList<String> list, HashMap<String, String> placeholders) {
            if (!list.isEmpty()) {
                MiscUtils.getInstance().executeConsoleCommands(user.getPlayerName(), list, placeholders);
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder("COMMAND_BLOCK"), new EditGUIValueList("Commands", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("List of console commands"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.isList(inject.getPath()) && !data.isConfigurationSection(inject.getPath())) {
                List<String> list = data.getStringList(inject.getPath());
                if (list != null) {
                    if (list.isEmpty()) {
                        warning(reward, inject, "No commands listed");
                    }
                    for (String str : list) {
                        if (str.startsWith("/")) {
                            warning(reward, inject, "Commands can not start with /");
                        }
                    }
                }
            }
        }
    }));
    injectedRewards.add(new RewardInjectConfigurationSection("Commands") {

        @SuppressWarnings("unchecked")
        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            ArrayList<String> consoleCommands = (ArrayList<String>) section.getList("Console", new ArrayList<String>());
            ArrayList<String> userCommands = (ArrayList<String>) section.getList("Player", new ArrayList<String>());
            if (!consoleCommands.isEmpty()) {
                MiscUtils.getInstance().executeConsoleCommands(user.getPlayerName(), consoleCommands, placeholders);
            }
            if (!userCommands.isEmpty()) {
                user.preformCommand(userCommands, placeholders);
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueList("Commands.Console", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Old style for console commands"))).addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueList("Commands.Player", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Execute commands as player"))));
    injectedRewards.add(new RewardInjectStringList("Javascripts") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, ArrayList<String> list, HashMap<String, String> placeholders) {
            if (!list.isEmpty()) {
                JavascriptEngine engine = new JavascriptEngine().addPlayer(user.getOfflinePlayer());
                for (String str : list) {
                    engine.execute(StringParser.getInstance().replacePlaceHolder(str, placeholders));
                }
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueList("Javascripts", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Javascript expressions to run"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Javascript") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (section.getBoolean("Enabled")) {
                if (new JavascriptEngine().addPlayer(user.getOfflinePlayer()).getBooleanValue(StringParser.getInstance().replacePlaceHolder(section.getString("Expression"), placeholders))) {
                    new RewardBuilder(section, "TrueRewards").withPrefix(reward.getName()).send(user);
                } else {
                    new RewardBuilder(section, "FalseRewards").withPrefix(reward.getName()).send(user);
                }
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("Javascript") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditJavascript() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Run javascript to run rewards based on expression return value of true/false"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Lucky") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            HashMap<Integer, String> luckyRewards = new HashMap<Integer, String>();
            for (String str : section.getKeys(false)) {
                if (StringParser.getInstance().isInt(str)) {
                    int num = Integer.parseInt(str);
                    if (num > 0) {
                        String path = "Lucky." + num;
                        luckyRewards.put(num, path);
                    }
                }
            }
            HashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
            for (Entry<Integer, String> entry : luckyRewards.entrySet()) {
                if (MiscUtils.getInstance().checkChance(1, entry.getKey())) {
                    map.put(entry.getValue(), entry.getKey());
                }
            }
            map = ArrayUtils.getInstance().sortByValuesStr(map, false);
            if (map.size() > 0) {
                if (reward.getConfig().getConfigData().getBoolean("OnlyOneLucky", false)) {
                    for (Entry<String, Integer> entry : map.entrySet()) {
                        new RewardBuilder(reward.getConfig().getConfigData(), entry.getKey()).withPlaceHolder(placeholders).send(user);
                        return null;
                    }
                } else {
                    for (Entry<String, Integer> entry : map.entrySet()) {
                        new RewardBuilder(reward.getConfig().getConfigData(), entry.getKey()).withPlaceHolder(placeholders).send(user);
                    }
                }
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("Lucky") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditLucky() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(getKey(), value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    })).priority(10).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
        }
    }.addPath("OnlyOneLucky")));
    injectedRewards.add(new RewardInjectConfigurationSection("Random") {

        @SuppressWarnings("unchecked")
        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (MiscUtils.getInstance().checkChance(section.getDouble("Chance", 100), 100)) {
                if (section.getBoolean("PickRandom", true)) {
                    ArrayList<String> rewards = (ArrayList<String>) section.getList("Rewards", new ArrayList<String>());
                    if (rewards != null) {
                        if (rewards.size() > 0) {
                            String reward1 = rewards.get(ThreadLocalRandom.current().nextInt(rewards.size()));
                            if (!reward1.equals("")) {
                                RewardHandler.getInstance().giveReward(user, reward1, new RewardOptions().setPlaceholders(placeholders));
                            }
                        }
                    }
                } else {
                    new RewardBuilder(reward.getConfig().getConfigData(), "Random.Rewards").withPrefix(reward.getName()).withPlaceHolder(placeholders).send(user);
                }
            } else {
                new RewardBuilder(reward.getConfig().getConfigData(), "Random.FallBack").withPrefix(reward.getName()).withPlaceHolder(placeholders).send(user);
            }
            return null;
        }
    }.priority(10));
    injectedRewards.add(new RewardInjectConfigurationSection("Rewards") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            new RewardBuilder(reward.getConfig().getConfigData(), "Rewards").withPrefix(reward.getName()).withPlaceHolder(placeholders).send(user);
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.DISPENSER), new EditGUIValueInventory("Rewards") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            openSubReward(clickEvent.getPlayer(), "Rewards", reward);
        }
    }.addLore("Sub rewards"))).priority(5).alwaysForce().postReward());
    injectedRewards.add(new RewardInjectStringList("RandomCommand") {

        @Override
        public String onRewardRequest(Reward r, AdvancedCoreUser user, ArrayList<String> list, HashMap<String, String> placeholders) {
            if (list.size() > 0) {
                MiscUtils.getInstance().executeConsoleCommands(user.getPlayer(), list.get(ThreadLocalRandom.current().nextInt(list.size())), placeholders);
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueList("RandomCommand", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Execute random command"))).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            List<String> list = data.getStringList(inject.getPath());
            if (list.size() == 0) {
                warning(reward, inject, "No rewards listed for random reward");
            } else if (list.size() == 1) {
                warning(reward, inject, "Only one reward listed for random reward");
            }
        }
    }));
    injectedRewards.add(new RewardInjectStringList("RandomReward") {

        @Override
        public String onRewardRequest(Reward r, AdvancedCoreUser user, ArrayList<String> list, HashMap<String, String> placeholders) {
            if (list.size() > 0) {
                String reward = list.get(ThreadLocalRandom.current().nextInt(list.size()));
                giveReward(user, reward, new RewardOptions().setPlaceholders(placeholders));
                return reward;
            }
            return null;
        }
    }.asPlaceholder("RandomReward").priority(90).addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueList("RandomReward", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
        }
    }.addLore("Execute random reward"))).postReward());
    injectedRewards.add(new RewardInjectConfigurationSection("TempPermission") {

        @Override
        public String onRewardRequested(Reward r, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            String perm = section.getString("Permission", "");
            int time = section.getInt("Expiration");
            if (!perm.isEmpty()) {
                if (time > 0) {
                    user.addPermission(perm, time);
                } else {
                    extraDebug("Time is 0");
                }
            } else {
                extraDebug("Permission is empty");
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("TempPermission") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditTempPermission() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Give temporary permission"))).priority(90).postReward());
    injectedRewards.add(new RewardInjectConfigurationSection("AdvancedRandomReward") {

        @Override
        public String onRewardRequested(Reward r, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            Set<String> keys = section.getKeys(false);
            ArrayList<String> rewards = ArrayUtils.getInstance().convert(keys);
            if (rewards.size() > 0) {
                String reward = rewards.get(ThreadLocalRandom.current().nextInt(rewards.size()));
                giveReward(user, section, reward, new RewardOptions().setPlaceholders(placeholders).setPrefix(r.getRewardName() + "_AdvancedRandomReward_"));
                return reward;
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("AdvancedRandomReward") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditAdvancedRandomReward() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Execute random reward"))).asPlaceholder("RandomReward").priority(90).postReward());
    injectedRewards.add(new RewardInjectStringList("Priority") {

        @Override
        public String onRewardRequest(Reward r, AdvancedCoreUser user, ArrayList<String> list, HashMap<String, String> placeholders) {
            for (String str : list) {
                Reward reward = RewardHandler.getInstance().getReward(str);
                if (reward.canGiveReward(user, new RewardOptions())) {
                    new RewardBuilder(reward).withPlaceHolder(placeholders).setIgnoreChance(true).setIgnoreRequirements(true).send(user);
                    return reward.getName();
                }
            }
            return null;
        }
    }.asPlaceholder("Priority").addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueList("Priority", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Execute first reward file that can be executed"))).postReward());
    injectedRewards.add(new RewardInjectConfigurationSection("Potions") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            for (String potion : section.getKeys(false)) {
                user.givePotionEffect(potion, section.getInt(potion + ".Duration", 1), section.getInt(potion + ".Amplifier", 1));
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAINTING), new EditGUIValueInventory("Potions") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditPotions() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Configure Potion Effects"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Title") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (section.getBoolean("Enabled")) {
                user.sendTitle(StringParser.getInstance().replacePlaceHolder(section.getString("Title"), placeholders), StringParser.getInstance().replacePlaceHolder(section.getString("SubTitle"), placeholders), section.getInt("FadeIn", 10), section.getInt("ShowTime", 50), section.getInt("FadeOut", 10));
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAINTING), new EditGUIValueInventory("Title") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditTitle() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Configure Title & SubTitle"))));
    injectedRewards.add(new RewardInjectConfigurationSection("BossBar") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (section.getBoolean("Enabled")) {
                user.sendBossBar(StringParser.getInstance().replacePlaceHolder(section.getString("Message", ""), placeholders), section.getString("Color", "BLUE"), section.getString("Style", "SOLID"), section.getDouble("Progress", .5), section.getInt("Delay", 30));
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder("DRAGON_HEAD"), new EditGUIValueInventory("BossBar") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditBossBar() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Configure bossbar"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Sound") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (section.getBoolean("Enabled")) {
                try {
                    user.playSound(section.getString("Sound"), (float) section.getDouble("Volume", 1.0), (float) section.getDouble("Pitch", 1.0));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.NOTE_BLOCK), new EditGUIValueInventory("Sound") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditSound() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Configure sound"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Effect") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (section.getBoolean("Enabled")) {
                user.playParticle(section.getString("Effect"), section.getInt("Data", 1), section.getInt("Particles", 1), section.getInt("Radius", 5));
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.DIAMOND), new EditGUIValueInventory("Effect") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditEffect() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Configure particle effect"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Firework") {

        @SuppressWarnings("unchecked")
        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            if (section.getBoolean("Enabled")) {
                FireworkHandler.getInstance().launchFirework(user.getPlayer().getLocation(), section.getInt("Power", 1), (ArrayList<String>) section.getList("Colors", new ArrayList<String>()), (ArrayList<String>) section.getList("FadeOutColor", new ArrayList<String>()), section.getBoolean("Trail"), section.getBoolean("Flicker"), (ArrayList<String>) section.getList("Types", new ArrayList<String>()));
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder("FIREWORK_ROCKET"), new EditGUIValueInventory("Firework") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditFirework() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Configure firework effect"))));
    injectedRewards.add(new RewardInjectConfigurationSection("Item") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            ItemBuilder builder = new ItemBuilder(section);
            builder.setCheckLoreLength(false);
            user.giveItem(builder);
            return null;
        }
    }.validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            String material = data.getString("Item.Material", "");
            if (material.isEmpty()) {
                warning(reward, inject, "No material is set on item");
            } else {
                try {
                    Material m = Material.matchMaterial(material.toUpperCase());
                    // change legacy item
                    if (m == null) {
                        m = Material.matchMaterial(material, true);
                        if (material != null) {
                            warning(reward, inject, "Found legacy material: " + material + ", please update material");
                        }
                    }
                } catch (NoSuchMethodError e) {
                }
            }
        }
    }));
    injectedRewards.add(new RewardInjectConfigurationSection("AdvancedPriority") {

        @Override
        public String onRewardRequested(Reward reward1, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            for (String keys : section.getKeys(false)) {
                Reward reward = RewardHandler.getInstance().getReward(section, keys, new RewardOptions());
                if (reward != null && reward.canGiveReward(user, new RewardOptions())) {
                    plugin.extraDebug("AdvancedPriority: Giving reward " + reward.getName());
                    reward.giveReward(user, new RewardOptions().withPlaceHolder(placeholders).setIgnoreChance(true).setIgnoreRequirements(true).setPrefix(reward1.getName() + "_AdvancedPriority"));
                    return reward.getName();
                } else {
                    plugin.extraDebug("AdvancedPriority: Can't give reward " + keys);
                }
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("AdvancedPriority") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditAdvancedPriority() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("AdvancedPriority will run first sub reward that it can, then ignore the rest of the sub rewards").addLore("Can be used for permission based rewards or chance based rewards"))).priority(10).postReward());
    injectedRewards.add(new RewardInjectConfigurationSection("AdvancedWorld") {

        @Override
        public String onRewardRequested(Reward reward1, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            for (String keys : section.getKeys(false)) {
                plugin.extraDebug("AdvancedWorld: Giving reward " + reward1.getName() + "_AdvancedWorld");
                section.set(keys + ".Worlds", ArrayUtils.getInstance().convert(new String[] { keys }));
                giveReward(user, section, keys, new RewardOptions().withPlaceHolder(placeholders).setPrefix(reward1.getName() + "_AdvancedWorld"));
            }
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("AdvancedWorld") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditAdvancedWorld() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("AdvancedReward will run rewards based worlds specified"))).priority(10).postReward());
    injectedRewards.add(new RewardInjectConfigurationSection("SpecialChance") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, HashMap<String, String> placeholders) {
            double totalChance = 0;
            LinkedHashMap<Double, String> map = new LinkedHashMap<Double, String>();
            for (String key : section.getKeys(false)) {
                String path = key;
                key = key.replaceAll("_", ".");
                if (StringParser.getInstance().isDouble(key)) {
                    double chance = Double.valueOf(key);
                    totalChance += chance;
                    map.put(chance, path);
                }
            }
            Set<Entry<Double, String>> copy = new HashSet<Entry<Double, String>>(map.entrySet());
            double currentNum = 0;
            map.clear();
            for (Entry<Double, String> entry : copy) {
                currentNum += entry.getKey();
                map.put(currentNum, entry.getValue());
            }
            double randomNum = ThreadLocalRandom.current().nextDouble(totalChance);
            for (Entry<Double, String> entry : map.entrySet()) {
                if (randomNum <= entry.getKey()) {
                    new RewardBuilder(section, entry.getValue()).withPrefix(reward.getName()).withPlaceHolder(placeholders).withPlaceHolder("chance", "" + entry.getKey()).send(user);
                    AdvancedCorePlugin.getInstance().debug("Giving special chance: " + entry.getValue() + ", Random numuber: " + randomNum + ", Total chance: " + totalChance);
                    return null;
                }
            }
            AdvancedCorePlugin.getInstance().debug("Failed to give special chance");
            return null;
        }
    }.addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("SpecialChance") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditSpecialChance() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Rewards based on chance"))).priority(10).postReward());
    injectedRewards.add(new RewardInjectKeys("RandomItem") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, Set<String> section, ConfigurationSection data, HashMap<String, String> placeholders) {
            if (section.size() > 0) {
                String item = ArrayUtils.getInstance().pickRandom(ArrayUtils.getInstance().convert(section));
                ItemBuilder builder = new ItemBuilder(data.getConfigurationSection(item));
                builder.setCheckLoreLength(false);
                user.giveItem(builder);
                return item;
            }
            return null;
        }
    }.asPlaceholder("RandomItem").priority(90).validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            for (String item : data.getConfigurationSection("RandomItem").getKeys(false)) {
                String material = data.getString("RandomItem." + item + ".Material", "");
                if (material.isEmpty()) {
                    warning(reward, inject, "No material is set on item: " + item);
                } else {
                    try {
                        Material m = Material.matchMaterial(material.toUpperCase());
                        // change legacy item
                        if (m == null) {
                            m = Material.matchMaterial(material.toUpperCase(), true);
                            if (material != null) {
                                warning(reward, inject, "Found legacy material: " + material + ", please update material on RandomItem." + item);
                            }
                        }
                    } catch (NoSuchMethodError e) {
                    }
                }
            }
        }
    }));
    injectedRewards.add(new RewardInjectBoolean("EnableChoices") {

        @Override
        public String onRewardRequest(Reward reward, AdvancedCoreUser user, boolean value, HashMap<String, String> placeholders) {
            if (value) {
                debug("Checking choice rewards");
                reward.checkRewardFile();
                String choice = user.getChoicePreference(reward.getName());
                if (choice.isEmpty() || choice.equalsIgnoreCase("none")) {
                    debug("No choice specified");
                    user.addUnClaimedChoiceReward(reward.getName());
                } else {
                    giveChoicesReward(reward, user, choice);
                }
            }
            return null;
        }
    }.priority(10).synchronize().validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.getBoolean("EnableChoices")) {
                if (data.getConfigurationSection("Choices").getKeys(false).size() <= 1) {
                    warning(reward, inject, "Not enough choices for choice rewards, 1 or less is not a choice");
                }
            }
        }
    }.addPath("Choices")).addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("Choices") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditChoices() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addCheckKey("EnableChoices").addLore("Give users a choice on the reward"))));
    injectedRewards.add(new RewardInjectKeys("Items") {

        @Override
        public String onRewardRequested(Reward reward, AdvancedCoreUser user, Set<String> section, ConfigurationSection data, HashMap<String, String> placeholders) {
            boolean oneChance = reward.getConfig().getConfigData().getBoolean("OnlyOneItemChance", false);
            if (section.size() > 0) {
                for (String str : section) {
                    ItemBuilder builder = new ItemBuilder(data.getConfigurationSection(str));
                    builder.setCheckLoreLength(false);
                    user.giveItem(builder.setPlaceholders(placeholders));
                    debug("Giving item " + str + ":" + builder.toString());
                    if (builder.isChancePass() && oneChance) {
                        return str;
                    }
                }
            }
            return "";
        }
    }.priority(90).asPlaceholder("Item").validator(new RewardInjectValidator() {

        @Override
        public void onValidate(Reward reward, RewardInject inject, ConfigurationSection data) {
            if (data.isConfigurationSection("Items")) {
                for (String item : data.getConfigurationSection("Items").getKeys(false)) {
                    String material = data.getString("Items." + item + ".Material", "");
                    if (material.isEmpty()) {
                        try {
                            Material.valueOf(item);
                        } catch (Exception e) {
                            warning(reward, inject, "No material is set on item: " + item);
                        }
                    } else {
                        try {
                            Material m = Material.matchMaterial(material.toUpperCase());
                            // check legacy
                            if (m == null) {
                                m = Material.matchMaterial(material, true);
                                if (m != null) {
                                    warning(reward, inject, "Found legacy material: " + material + ", please update material");
                                } else {
                                    warning(reward, inject, "Invalid material set: " + material);
                                }
                            }
                        } catch (NoSuchMethodError e) {
                        }
                    }
                    if (data.getInt("Items." + item + ".Amount", 0) == 0) {
                        if (data.getInt("Items." + item + ".MinAmount", 0) == 0 && data.getInt("Items." + item + ".MaxAmount") == 0) {
                            warning(reward, inject, "No amount on item: " + item);
                        }
                    }
                }
            } else {
                warning(reward, inject, "Invalid item section");
            }
        }
    }.addPath("OnlyOneItemChance")).addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueInventory("Items") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditItems() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Edit items"))));
    for (RewardInject reward : injectedRewards) {
        reward.setInternalReward(true);
    }
    sortInjectedRewards();
}
Also used : RewardEditSound(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditSound) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) RewardEditMoney(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditMoney) ClickEvent(com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent) ArrayList(java.util.ArrayList) RewardEditChoices(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditChoices) RewardInjectDouble(com.bencodez.advancedcore.api.rewards.injected.RewardInjectDouble) RewardEditAdvancedPriority(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditAdvancedPriority) RewardInjectString(com.bencodez.advancedcore.api.rewards.injected.RewardInjectString) EditGUIValueString(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString) RequirementInjectString(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectString) RewardInjectKeys(com.bencodez.advancedcore.api.rewards.injected.RewardInjectKeys) LinkedHashMap(java.util.LinkedHashMap) RewardEditSpecialChance(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditSpecialChance) RewardEditAdvancedWorld(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditAdvancedWorld) RewardEditPotions(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditPotions) HashSet(java.util.HashSet) RewardInjectStringList(com.bencodez.advancedcore.api.rewards.injected.RewardInjectStringList) Player(org.bukkit.entity.Player) JavascriptEngine(com.bencodez.advancedcore.api.javascript.JavascriptEngine) RewardEditFirework(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditFirework) RewardInjectInt(com.bencodez.advancedcore.api.rewards.injected.RewardInjectInt) RequirementInjectDouble(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectDouble) RewardInjectDouble(com.bencodez.advancedcore.api.rewards.injected.RewardInjectDouble) RewardEditMessages(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditMessages) ItemBuilder(com.bencodez.advancedcore.api.item.ItemBuilder) RewardEditEXPLevels(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditEXPLevels) EditGUIValueList(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueList) RewardEditEXP(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditEXP) EditGUIButton(com.bencodez.advancedcore.api.inventory.editgui.EditGUIButton) RewardEditJavascript(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditJavascript) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) RequirementInjectConfigurationSection(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectConfigurationSection) RewardInjectConfigurationSection(com.bencodez.advancedcore.api.rewards.injected.RewardInjectConfigurationSection) RewardEditTempPermission(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditTempPermission) Set(java.util.Set) HashSet(java.util.HashSet) RewardEditActionBar(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditActionBar) DecimalFormat(java.text.DecimalFormat) RewardEditItems(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditItems) RewardEditAdvancedRandomReward(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditAdvancedRandomReward) RewardEditEffect(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditEffect) Entry(java.util.Map.Entry) RewardEditBossBar(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditBossBar) EditGUIValueInventory(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueInventory) RewardInjectValidator(com.bencodez.advancedcore.api.rewards.injected.RewardInjectValidator) RewardEditLucky(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditLucky) RewardInjectString(com.bencodez.advancedcore.api.rewards.injected.RewardInjectString) EditGUIValueString(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString) Material(org.bukkit.Material) RewardInjectBoolean(com.bencodez.advancedcore.api.rewards.injected.RewardInjectBoolean) FileDirectoryException(com.bencodez.advancedcore.api.exceptions.FileDirectoryException) AdvancedCoreUser(com.bencodez.advancedcore.api.user.AdvancedCoreUser) RewardInjectConfigurationSection(com.bencodez.advancedcore.api.rewards.injected.RewardInjectConfigurationSection) RewardInject(com.bencodez.advancedcore.api.rewards.injected.RewardInject) RewardEditAdvancedRandomReward(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditAdvancedRandomReward) RewardEditTitle(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditTitle)

Example 2 with JavascriptEngine

use of com.bencodez.advancedcore.api.javascript.JavascriptEngine in project AdvancedCore by BenCodez.

the class StringUtils method replaceJavascript.

@Deprecated
public String replaceJavascript(String text, JavascriptEngine engine) {
    String msg = "";
    if (containsIgnorecase(text, "[Javascript=")) {
        if (engine == null) {
            engine = new JavascriptEngine();
        }
        int lastIndex = 0;
        int startIndex = 0;
        int num = 0;
        while (startIndex != -1) {
            startIndex = text.indexOf("[Javascript=", lastIndex);
            int endIndex = -1;
            if (startIndex != -1) {
                if (num != 0) {
                    msg += text.substring(lastIndex + 1, startIndex);
                } else {
                    msg += text.substring(lastIndex, startIndex);
                }
                num++;
                endIndex = text.indexOf("]", startIndex);
                String str = text.substring(startIndex + "[Javascript=".length(), endIndex);
                // plugin.debug(startIndex + ":" + endIndex + " from " +
                // text + " to " + str + " currently " + msg);
                String script = engine.getStringValue(str);
                if (script == null) {
                    script = "" + engine.getBooleanValue(str);
                }
                if (script != null) {
                    msg += script;
                }
                lastIndex = endIndex;
            }
        }
        msg += text.substring(lastIndex + 1);
    } else {
        msg = text;
    }
    // plugin.debug(msg);
    return msg;
}
Also used : JavascriptEngine(com.bencodez.advancedcore.api.javascript.JavascriptEngine)

Example 3 with JavascriptEngine

use of com.bencodez.advancedcore.api.javascript.JavascriptEngine in project AdvancedCore by BenCodez.

the class CommandLoader method getBasicAdminCommands.

public ArrayList<CommandHandler> getBasicAdminCommands(String permPrefix) {
    ArrayList<CommandHandler> cmds = new ArrayList<CommandHandler>();
    cmds.add(new CommandHandler(new String[] { "RunCMD", "All", "(List)" }, permPrefix + ".RunCMD.All", "Run command for every user, use %player% for player") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            String str = "";
            for (int i = 2; i < args.length; i++) {
                str += args[i] + " ";
            }
            final String cmd = str;
            ArrayList<AdvancedCoreUser> users = new ArrayList<AdvancedCoreUser>();
            for (String uuid : plugin.getUserManager().getAllUUIDs()) {
                AdvancedCoreUser user = plugin.getUserManager().getUser(UUID.fromString(uuid));
                user.dontCache();
                users.add(user);
                Bukkit.getScheduler().runTask(plugin, new Runnable() {

                    @Override
                    public void run() {
                        Bukkit.getServer().dispatchCommand(sender, StringParser.getInstance().replacePlaceHolder(cmd, "player", user.getPlayerName()));
                    }
                });
            }
        }
    });
    cmds.add(new CommandHandler(new String[] { "GiveAll", "(reward)" }, permPrefix + ".GiveAll", "Give all users a reward") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            Reward reward = plugin.getRewardHandler().getReward(args[1]);
            ArrayList<AdvancedCoreUser> users = new ArrayList<AdvancedCoreUser>();
            for (String uuid : plugin.getUserManager().getAllUUIDs()) {
                AdvancedCoreUser user = plugin.getUserManager().getUser(UUID.fromString(uuid));
                user.dontCache();
                users.add(user);
            }
            for (AdvancedCoreUser user : users) {
                new RewardBuilder(reward).send(user);
            }
            sendMessage(sender, "&cGave all players reward file " + args[1]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "GiveAllOnline", "(reward)" }, permPrefix + ".GiveAllOnline", "Give all users a reward") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            Reward reward = plugin.getRewardHandler().getReward(args[1]);
            for (Player p : Bukkit.getOnlinePlayers()) {
                AdvancedCoreUser user = plugin.getUserManager().getUser(p);
                new RewardBuilder(reward).send(user);
            }
        }
    });
    cmds.add(new CommandHandler(new String[] { "GiveReward", "(Player)", "(Reward)" }, permPrefix + ".GiveReward", "Give a player a reward file", true) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
            plugin.getRewardHandler().giveReward(user, args[2], new RewardOptions().setOnline(user.isOnline()));
            sendMessage(sender, "&cGave " + args[1] + " the reward file " + args[2]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)", "ForceReward", "(Reward)" }, permPrefix + ".GiveReward", "Give a player a reward file", true) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            if (args[1].equalsIgnoreCase("all")) {
                Reward reward = plugin.getRewardHandler().getReward(args[3]);
                ArrayList<AdvancedCoreUser> users = new ArrayList<AdvancedCoreUser>();
                for (String uuid : plugin.getUserManager().getAllUUIDs()) {
                    AdvancedCoreUser user = plugin.getUserManager().getUser(UUID.fromString(uuid));
                    user.dontCache();
                    users.add(user);
                }
                for (AdvancedCoreUser user : users) {
                    new RewardBuilder(reward).send(user);
                }
                sendMessage(sender, "&cGave all players reward file " + args[3]);
            } else {
                AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
                plugin.getRewardHandler().giveReward(user, args[3], new RewardOptions().setOnline(user.isOnline()));
                sender.sendMessage("&cGave " + args[1] + " the reward file " + args[3]);
            }
        }
    });
    cmds.add(new CommandHandler(new String[] { "GiveReward", "(Player)", "(Reward)", "(Text)", "(Text)" }, permPrefix + ".GiveReward", "Give a player a reward file and set a placeholder", true) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
            plugin.getRewardHandler().giveReward(user, args[2], new RewardOptions().setOnline(user.isOnline()).addPlaceholder(args[3], args[4]));
            sender.sendMessage("&cGave " + args[1] + " the reward file " + args[2]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "Report" }, permPrefix + ".Report", "Create Report File") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            ZipCreator.getInstance().createReport();
            sender.sendMessage("Created zip file");
        }
    });
    cmds.add(new CommandHandler(new String[] { "ClearOfflineRewards" }, permPrefix + ".ClearOfflineRewards", "Clear offline rewards", true, true) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            sendMessage(sender, "&cStarting to clear offline rewards");
            plugin.getUserManager().removeAllKeyValues(plugin.getUserManager().getOfflineRewardsPath(), DataType.STRING);
            sendMessage(sender, "&cFinished clearing offline rewards");
        }
    });
    cmds.add(new CommandHandler(new String[] { "GUI" }, permPrefix + ".AdminGUI", "Open AdminGUI", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdminGUI.getInstance().openGUI((Player) sender);
        }
    });
    cmds.add(new CommandHandler(new String[] { "Rewards" }, permPrefix + ".RewardEdit", "Open RewardGUI", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            RewardEditGUI.getInstance().openRewardsGUI((Player) sender);
        }
    });
    cmds.add(new CommandHandler(new String[] { "User" }, permPrefix + ".UserEdit", "Open UserGUI", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            UserGUI.getInstance().openUsersGUI((Player) sender);
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)" }, permPrefix + ".UserEdit", "Open UserGUI", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            UserGUI.getInstance().openUserGUI((Player) sender, args[1]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)", "RemoveTempPermissions" }, permPrefix + ".RemoveTempPermission", "Remove temp permissions") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            plugin.getPermissionHandler().removePermission(UUID.fromString(PlayerUtils.getInstance().getUUID(args[1])));
            sendMessage(sender, "&cRemoved temporary permissions from " + args[1]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)", "AddTempPermissions", "(Text)", "(Number)" }, permPrefix + ".AddTempPermission", "Add temp permission for number of seconds") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            plugin.getPermissionHandler().addPermission(UUID.fromString(PlayerUtils.getInstance().getUUID(args[1])), args[3], Integer.valueOf(args[4]));
            sendMessage(sender, "&cAdded temporary permission to " + args[1] + " for " + args[4]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)", "AddTempPermissions", "(Text)" }, permPrefix + ".AddTempPermission", "Add temp permission") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            plugin.getPermissionHandler().addPermission(UUID.fromString(PlayerUtils.getInstance().getUUID(args[1])), args[3]);
            sendMessage(sender, "&cAdded temporary permission to " + args[1]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "Report" }, permPrefix + ".Report", "Create a zip file to send for debuging") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            ZipCreator.getInstance().createReport();
            sender.sendMessage("Created Zip File!");
        }
    });
    cmds.add(new CommandHandler(new String[] { "UserRemove", "(player)" }, permPrefix + ".UserRemove", "Remove User") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            sendMessage(sender, "&cRemoving " + args[1]);
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
            user.getData().remove();
            sendMessage(sender, "&cRemoved " + args[1]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "UserUUIDRemove", "(uuid)" }, permPrefix + ".UserRemove", "Remove User") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            sendMessage(sender, "&cRemoving " + args[1]);
            AdvancedCoreUser user = plugin.getUserManager().getUser(UUID.fromString(args[1]));
            user.getData().remove();
            sendMessage(sender, "&cRemoved " + args[1]);
        }
    });
    cmds.add(new CommandHandler(new String[] { "ClearCache" }, permPrefix + ".ClearCache", "Clear MySQL Cache") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            if (plugin.getStorageType().equals(UserStorage.MYSQL)) {
                if (plugin.getMysql() != null) {
                    plugin.getMysql().clearCacheBasic();
                } else {
                    sender.sendMessage(StringParser.getInstance().colorize("&cMySQL not loaded"));
                }
            }
            plugin.getUserManager().getDataManager().clearCache();
            sender.sendMessage(StringParser.getInstance().colorize("&cCache cleared"));
        }
    });
    cmds.add(new CommandHandler(new String[] { "Purge" }, permPrefix + ".Purge", "Purge Data") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            plugin.getUserManager().purgeOldPlayersNow();
            sendMessage(sender, "&cPurged data");
        }
    });
    if (!plugin.getJenkinsSite().isEmpty()) {
        cmds.add(new CommandHandler(new String[] { "DownloadJenkins" }, permPrefix + ".Download", "Download from jenkins. Please use at your own risk") {

            @Override
            public void execute(CommandSender sender, String[] args) {
                if (plugin.getOptions().isEnableJenkins() && !plugin.getJenkinsSite().isEmpty()) {
                    sender.sendMessage(StringParser.getInstance().colorize("&cAttempting to download from jenkins... restart server to fully update, Note: USE THESE DEV BUILDS AT YOUR OWN RISK"));
                    UpdateDownloader.getInstance().downloadFromJenkins(plugin.getJenkinsSite(), plugin.getName());
                    sender.sendMessage(StringParser.getInstance().colorize("&cDownloaded jar"));
                } else {
                    sendMessage(sender, "&cNot enabled, please enable to use this. Note: USE THESE DEV BUILDS AT YOUR OWN RISK");
                }
            }
        });
    }
    cmds.add(new CommandHandler(new String[] { "ForceTimeChanged", "(TimeType)" }, permPrefix + ".ForceTimeChange", "Force time change, use at your own risk!", true, true) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            try {
                TimeType time = TimeType.getTimeType(args[1]);
                sendMessage(sender, "&cForcing time change for " + time.toString() + ". May take awhile to process");
                plugin.getTimeChecker().forceChanged(time);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    cmds.add(new CommandHandler(new String[] { "Javascript", "(List)" }, permPrefix + ".Javascript", "Execute javascript") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            String str = "";
            for (int i = 1; i < args.length; i++) {
                str += args[i] + " ";
            }
            JavascriptEngine engine = new JavascriptEngine();
            engine.addPlayer(sender);
            sendMessage(sender, "&cJavascript result: " + engine.getStringValue(str.trim()));
        }
    });
    cmds.add(new CommandHandler(new String[] { "SetRequestMethod", "(RequestMethod)" }, permPrefix + ".SetRequestMethod", "SetRequestMethod", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser((Player) sender);
            InputMethod method = InputMethod.getMethod(args[1]);
            if (method == null) {
                user.sendMessage("&cInvalid request method: " + args[1]);
            } else {
                user.setUserInputMethod(method);
                user.sendMessage("&cRequest method set to " + method.toString());
            }
        }
    });
    cmds.add(new CommandHandler(new String[] { "SetRequestMethod" }, permPrefix + ".SetRequestMethod", "SetRequestMethod", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            ArrayList<String> methods = new ArrayList<String>();
            for (InputMethod method : InputMethod.values()) {
                methods.add(method.toString());
            }
            new ValueRequest(InputMethod.INVENTORY).requestString((Player) sender, "", ArrayUtils.getInstance().convert(methods), false, new StringListener() {

                @Override
                public void onInput(Player player, String value) {
                    AdvancedCoreUser user = plugin.getUserManager().getUser(player);
                    user.setUserInputMethod(InputMethod.getMethod(value));
                }
            });
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "All", "SetData", "(text)", "(text)" }, permPrefix + ".SetAllData", "Set all users data") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            String data = args[4];
            if (data.equalsIgnoreCase("\"\"")) {
                data = "";
            }
            for (String uuid : plugin.getUserManager().getAllUUIDs()) {
                AdvancedCoreUser user = plugin.getUserManager().getUser(UUID.fromString(uuid));
                user.dontCache();
                user.getData().setString(args[3], data);
            }
            sender.sendMessage(StringParser.getInstance().colorize("&cSet all users " + args[3] + " to " + args[4]));
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(player)", "SetData", "(text)", "(text)" }, permPrefix + ".SetData", "Set user data") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
            String data = args[4];
            if (data.equalsIgnoreCase("\"\"")) {
                data = "";
            }
            user.getData().setString(args[3], data);
            sender.sendMessage(StringParser.getInstance().colorize("&cSet " + args[3] + " for " + args[1] + " to " + args[4]));
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)", "ViewData" }, permPrefix + ".ViewData", "View playerdata") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
            for (String key : user.getData().getKeys()) {
                String str = user.getData().getString(key, true);
                if (plugin.getOptions().getStorageType().equals(UserStorage.MYSQL)) {
                    if (plugin.getMysql().isIntColumn(key)) {
                        str = "" + user.getData().getInt(key, true);
                    }
                }
                sendMessage(sender, "&c&l" + key + " &c" + str);
            }
        }
    });
    cmds.add(new CommandHandler(new String[] { "User", "(Player)", "HasPermission", "(Text)" }, permPrefix + ".HasPermission", "View playerdata") {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[1]);
            sendMessage(sender, "User " + args[1] + " permission " + args[3] + ":" + user.hasPermission(args[3]));
        }
    });
    cmds.add(new CommandHandler(new String[] { "Choices", "SetPreference", "(ChoiceReward)", "(String)", "(Player)" }, permPrefix + ".ChoicesSetPreferenceOther", "Let user pick his choice preferences", false) {

        @Override
        public void execute(CommandSender sender, String[] args) {
            AdvancedCoreUser user = plugin.getUserManager().getUser(args[4]);
            user.setChoicePreference(args[2], args[3]);
            user.sendMessage("&cPreference set to " + args[3] + " for " + args[4]);
        }
    });
    if (plugin.isLoadUserData()) {
        cmds.add(new CommandHandler(new String[] { "ConvertToData", "(UserStorage)" }, permPrefix + ".Commands.AdminVote.ConvertToData", "Convert user storage from current storage type the one specificed", true, true) {

            @Override
            public void execute(CommandSender sender, String[] args) {
                sendMessage(sender, "&cStarting convert from " + plugin.getStorageType().toString() + " to " + args[1]);
                plugin.convertDataStorage(plugin.getStorageType(), UserStorage.value(args[1]));
                sendMessage(sender, "&cFinished converting");
            }
        });
        cmds.add(new CommandHandler(new String[] { "ConvertFromData", "(UserStorage)" }, permPrefix + ".Commands.AdminVote.ConvertFromData", "Convert user storage from current storage type from the one specificed", true, true) {

            @Override
            public void execute(CommandSender sender, String[] args) {
                sendMessage(sender, "&cStarting convert from " + args[1] + " to " + plugin.getStorageType().toString());
                plugin.convertDataStorage(UserStorage.value(args[1]), plugin.getStorageType());
                sendMessage(sender, "&cFinished converting");
            }
        });
    }
    for (CommandHandler cmd : cmds) {
        cmd.setAdvancedCoreCommand(true);
    }
    return cmds;
}
Also used : Player(org.bukkit.entity.Player) ArrayList(java.util.ArrayList) JavascriptEngine(com.bencodez.advancedcore.api.javascript.JavascriptEngine) CommandHandler(com.bencodez.advancedcore.api.command.CommandHandler) ValueRequest(com.bencodez.advancedcore.api.valuerequest.ValueRequest) TimeType(com.bencodez.advancedcore.api.time.TimeType) AdvancedCoreUser(com.bencodez.advancedcore.api.user.AdvancedCoreUser) RewardBuilder(com.bencodez.advancedcore.api.rewards.RewardBuilder) RewardOptions(com.bencodez.advancedcore.api.rewards.RewardOptions) InputMethod(com.bencodez.advancedcore.api.valuerequest.InputMethod) CommandSender(org.bukkit.command.CommandSender) Reward(com.bencodez.advancedcore.api.rewards.Reward) StringListener(com.bencodez.advancedcore.api.valuerequest.listeners.StringListener)

Example 4 with JavascriptEngine

use of com.bencodez.advancedcore.api.javascript.JavascriptEngine in project AdvancedCore by BenCodez.

the class RewardHandler method loadInjectedRequirements.

public void loadInjectedRequirements() {
    injectedRequirements.add(new RequirementInjectDouble("Chance", 100) {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, double num, RewardOptions rewardOptions) {
            if (rewardOptions.isIgnoreChance()) {
                return true;
            }
            return MiscUtils.getInstance().checkChance(num, 100);
        }
    }.priority(100).addEditButton(new EditGUIButton(new ItemBuilder("DROPPER"), new EditGUIValueNumber("Chance", null) {

        @Override
        public void setValue(Player player, Number value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value.intValue());
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Set chance for reward to execute"))).validator(new RequirementInjectValidator() {

        @Override
        public void onValidate(Reward reward, RequirementInject inject, ConfigurationSection data) {
            if (data.getDouble(inject.getPath(), 0) == 100) {
                warning(reward, inject, "Chance is 100, if intended then remove the chance option, as it's unneeded");
            } else if (data.getDouble(inject.getPath(), 0) > 100) {
                warning(reward, inject, "Chance is greater than 100, this will always give the reward");
            } else if (data.getDouble(inject.getPath(), 1) == 0) {
                warning(reward, inject, "Chance can not be 0");
            } else if (data.getDouble(inject.getPath(), 1) < 0) {
                warning(reward, inject, "Chance can not be negative");
            }
        }
    }));
    injectedRequirements.add(new RequirementInjectInt("RewardExpiration", -1) {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, int num, RewardOptions rewardOptions) {
            if (rewardOptions.getPlaceholders().containsKey("ExecDate") && num > 0) {
                long execDate = Long.parseLong(rewardOptions.getPlaceholders().get("ExecDate"));
                debug("ExecDate: " + execDate + ", plus time: " + (execDate + num * 60 * 1000) + ", current time: " + System.currentTimeMillis());
                if (execDate + num * 60 * 1000 > System.currentTimeMillis()) {
                    return true;
                } else {
                    return false;
                }
            }
            return true;
        }
    }.priority(100).addEditButton(new EditGUIButton(new ItemBuilder("CLOCK"), new EditGUIValueNumber("RewardExpiration", null) {

        @Override
        public void setValue(Player player, Number value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value.intValue());
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Time before reward expires, if not executed").addLore("In minutes"))));
    injectedRequirements.add(new RequirementInjectString("Permission", "") {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, String str, RewardOptions rewardOptions) {
            if (!reward.getConfig().getRequirePermission()) {
                return true;
            }
            if (str.isEmpty()) {
                str = "AdvancedCore.Reward." + reward.getName();
            }
            boolean reverse = false;
            if (str.startsWith("!")) {
                reverse = true;
                str = str.substring(1);
            }
            boolean perm = PlayerUtils.getInstance().hasServerPermission(UUID.fromString(user.getUUID()), str);
            if (reverse) {
                perm = !perm;
            }
            if (!perm) {
                plugin.getLogger().info(user.getPlayerName() + " does not have permission " + str + " to get reward " + reward.getName() + ", reverse: " + reverse);
                return false;
            }
            return true;
        }
    }.priority(100).alwaysForce().addEditButton(new EditGUIButton(new ItemBuilder("IRON_DOOR"), new EditGUIValueString("Permission", null) {

        @Override
        public void setValue(Player player, String value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Set permission required to be given, set RequirePermission to true if using this"))).addEditButton(new EditGUIButton(new EditGUIValueBoolean("RequirePermission", null) {

        @Override
        public void setValue(Player player, boolean value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("If true, permission is required to run reward"))).validator(new RequirementInjectValidator() {

        @Override
        public void onValidate(Reward reward, RequirementInject inject, ConfigurationSection data) {
            if (!data.getBoolean("RequirePermission", false)) {
                if (!data.getString("Permission", "").isEmpty()) {
                    warning(reward, inject, "Detected permission set but RequirePermission is false");
                }
            }
        }
    }.addPath("RequirePermission")));
    injectedRequirements.add(new RequirementInjectString("Server", "") {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, String str, RewardOptions rewardOptions) {
            // set server to match
            String serverToMatch = str;
            boolean hadPlaceholder = false;
            if (str.isEmpty()) {
                if (rewardOptions.getPlaceholders().containsKey("Server")) {
                    serverToMatch = rewardOptions.getPlaceholders().get("Server");
                    hadPlaceholder = true;
                } else if (!rewardOptions.getServer().isEmpty()) {
                    serverToMatch = rewardOptions.getServer();
                }
            }
            String currentServer = AdvancedCorePlugin.getInstance().getOptions().getServer();
            if (!serverToMatch.isEmpty()) {
                debug("Current Server: " + currentServer + ", ServerToMatch: " + serverToMatch);
                boolean matched = serverToMatch.equalsIgnoreCase(currentServer);
                if (!matched && !hadPlaceholder) {
                    // add server for offline reward
                    rewardOptions.addPlaceholder("Server", serverToMatch);
                }
                return matched;
            }
            return true;
        }
    }.priority(100).allowReattempt().alwaysForceNoData().addEditButton(new EditGUIButton(new ItemBuilder(Material.PAPER), new EditGUIValueString("Server", null) {

        @Override
        public void setValue(Player player, String value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
        }
    }.addOptions(Bukkit.getServer().getName()).addLore("Server to execute reward on"))));
    injectedRequirements.add(new RequirementInjectStringList("Worlds", new ArrayList<String>()) {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, ArrayList<String> worlds, RewardOptions rewardOptions) {
            if (worlds.isEmpty()) {
                return true;
            }
            Player player = user.getPlayer();
            if (player == null) {
                return false;
            }
            reward.checkRewardFile();
            String world = player.getWorld().getName();
            if (worlds.contains(world)) {
                return true;
            }
            user.setCheckWorld(true);
            return false;
        }
    }.priority(100).allowReattempt().alwaysForce().addEditButton(new EditGUIButton(new ItemBuilder("END_PORTAL_FRAME"), new EditGUIValueList("Worlds", null) {

        @Override
        public void setValue(Player player, ArrayList<String> value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addLore("Worlds to execute reward in, only executes into one reward"))).validator(new RequirementInjectValidator() {

        @Override
        @SuppressWarnings("unchecked")
        public void onValidate(Reward reward, RequirementInject inject, ConfigurationSection data) {
            ArrayList<String> list = (ArrayList<String>) data.getList("Worlds", null);
            if (list != null) {
                if (list.isEmpty()) {
                    warning(reward, inject, "No worlds were listed");
                }
            }
        }
    }));
    injectedRequirements.add(new RequirementInjectString("RewardType", "BOTH") {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, String type, RewardOptions rewardOptions) {
            if (rewardOptions.isOnline()) {
                if (type.equalsIgnoreCase("offline")) {
                    plugin.debug("Reward Type Don't match");
                    return false;
                }
            } else {
                if (type.equalsIgnoreCase("online")) {
                    plugin.debug("Reward Type Don't match");
                    return false;
                }
            }
            return true;
        }
    }.priority(100).addEditButton(new EditGUIButton(new ItemBuilder("REDSTONE_TORCH"), new EditGUIValueString("RewardType", null) {

        @Override
        public void setValue(Player player, String value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
            reward.reOpenEditGUI(player);
        }
    }.addOptions("ONLINE", "OFFLINE", "BOTH").addLore("Define whether should execute if player was offline/online"))));
    injectedRequirements.add(new RequirementInjectString("JavascriptExpression", "") {

        @Override
        public boolean onRequirementsRequest(Reward reward, AdvancedCoreUser user, String expression, RewardOptions rewardOptions) {
            if (expression.equals("") || new JavascriptEngine().addPlayer(user.getOfflinePlayer()).getBooleanValue(StringParser.getInstance().replacePlaceHolder(expression, rewardOptions.getPlaceholders()))) {
                return true;
            }
            return false;
        }
    }.priority(90).addEditButton(new EditGUIButton(new ItemBuilder("DETECTOR_RAIL"), new EditGUIValueString("JavascriptExpression", null) {

        @Override
        public void setValue(Player player, String value) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            reward.setValue(getKey(), value);
            plugin.reloadAdvancedCore(false);
        }
    }.addLore("Javascript expression required to run reward"))).validator(new RequirementInjectValidator() {

        @Override
        public void onValidate(Reward reward, RequirementInject inject, ConfigurationSection data) {
            String str = data.getString("JavascriptExpression", null);
            if (str != null) {
                if (str.isEmpty()) {
                    warning(reward, inject, "No javascript expression set");
                }
            }
        }
    }));
    injectedRequirements.add(new RequirementInjectConfigurationSection("LocationDistance") {

        @Override
        public boolean onRequirementsRequested(Reward reward, AdvancedCoreUser user, ConfigurationSection section, RewardOptions rewardOptions) {
            if (!user.isOnline()) {
                plugin.debug("user not online");
                return false;
            }
            Location loc = new Location(Bukkit.getWorld(section.getString("World")), section.getInt("X"), section.getInt("Y"), section.getInt("Z"));
            Location pLoc = user.getPlayer().getLocation();
            if (!loc.getWorld().getName().equals(pLoc.getWorld().getName())) {
                plugin.debug("Worlds don't match");
                return false;
            }
            if (pLoc.distance(loc) < section.getInt("Distance")) {
                return true;
            }
            return false;
        }
    }.priority(90).validator(new RequirementInjectValidator() {

        @Override
        public void onValidate(Reward reward, RequirementInject inject, ConfigurationSection data) {
            if (!data.isConfigurationSection("LocationDistance")) {
                return;
            }
            ConfigurationSection section = data.getConfigurationSection("LocationDistance");
            try {
                new Location(Bukkit.getWorld(section.getString("World")), section.getInt("X"), section.getInt("Y"), section.getInt("Z"));
            } catch (Exception e) {
                warning(reward, inject, "Failed to get location for LocationDistance");
                e.printStackTrace();
            }
            if (section.getInt("Distance") < 0) {
                warning(reward, inject, "Invalid distance for LocationDistance");
            }
        }
    }).addEditButton(new EditGUIButton(new ItemBuilder("MAP"), new EditGUIValueInventory("LocationDistance") {

        @Override
        public void openInventory(ClickEvent clickEvent) {
            RewardEditData reward = (RewardEditData) getInv().getData("Reward");
            new RewardEditLocationDistance() {

                @Override
                public void setVal(String key, Object value) {
                    RewardEditData reward = (RewardEditData) getInv().getData("Reward");
                    reward.setValue(key, value);
                    plugin.reloadAdvancedCore(false);
                }
            }.open(clickEvent.getPlayer(), reward);
        }
    }.addLore("Require player to be within a certain distance of locaction to get reward"))));
    for (RequirementInject reward : injectedRequirements) {
        reward.setInternalReward(true);
    }
    sortInjectedRequirements();
}
Also used : EditGUIValueBoolean(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueBoolean) ClickEvent(com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent) RequirementInjectString(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectString) ArrayList(java.util.ArrayList) RewardEditLocationDistance(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditLocationDistance) RequirementInjectStringList(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectStringList) RewardInjectString(com.bencodez.advancedcore.api.rewards.injected.RewardInjectString) EditGUIValueString(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString) RequirementInjectString(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectString) RequirementInjectConfigurationSection(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectConfigurationSection) RequirementInjectInt(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectInt) EditGUIValueNumber(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueNumber) EditGUIValueInventory(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueInventory) RequirementInjectValidator(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectValidator) Player(org.bukkit.entity.Player) EditGUIValueString(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString) RequirementInjectDouble(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectDouble) JavascriptEngine(com.bencodez.advancedcore.api.javascript.JavascriptEngine) FileDirectoryException(com.bencodez.advancedcore.api.exceptions.FileDirectoryException) AdvancedCoreUser(com.bencodez.advancedcore.api.user.AdvancedCoreUser) ItemBuilder(com.bencodez.advancedcore.api.item.ItemBuilder) EditGUIValueList(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueList) EditGUIButton(com.bencodez.advancedcore.api.inventory.editgui.EditGUIButton) EditGUIValueNumber(com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueNumber) RewardEditAdvancedRandomReward(com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditAdvancedRandomReward) RequirementInject(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInject) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) RequirementInjectConfigurationSection(com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectConfigurationSection) RewardInjectConfigurationSection(com.bencodez.advancedcore.api.rewards.injected.RewardInjectConfigurationSection) Location(org.bukkit.Location)

Example 5 with JavascriptEngine

use of com.bencodez.advancedcore.api.javascript.JavascriptEngine in project AdvancedCore by BenCodez.

the class StringParser method replaceJavascript.

public String replaceJavascript(String text, JavascriptEngine engine) {
    String msg = "";
    if (containsIgnorecase(text, "[Javascript=")) {
        if (engine == null) {
            engine = new JavascriptEngine();
        }
        int lastIndex = 0;
        int startIndex = 0;
        int num = 0;
        while (startIndex != -1) {
            startIndex = text.indexOf("[Javascript=", lastIndex);
            int endIndex = -1;
            if (startIndex != -1) {
                if (num != 0) {
                    msg += text.substring(lastIndex + 1, startIndex);
                } else {
                    msg += text.substring(lastIndex, startIndex);
                }
                num++;
                endIndex = text.indexOf("]", startIndex);
                String str = text.substring(startIndex + "[Javascript=".length(), endIndex);
                // plugin.debug(startIndex + ":" + endIndex + " from " +
                // text + " to " + str + " currently " + msg);
                String script = engine.getStringValue(str);
                if (script == null) {
                    script = "" + engine.getBooleanValue(str);
                }
                if (script != null) {
                    msg += script;
                }
                lastIndex = endIndex;
            }
        }
        msg += text.substring(lastIndex + 1);
    } else {
        msg = text;
    }
    // plugin.debug(msg);
    return msg;
}
Also used : JavascriptEngine(com.bencodez.advancedcore.api.javascript.JavascriptEngine)

Aggregations

JavascriptEngine (com.bencodez.advancedcore.api.javascript.JavascriptEngine)5 FileDirectoryException (com.bencodez.advancedcore.api.exceptions.FileDirectoryException)2 ClickEvent (com.bencodez.advancedcore.api.inventory.BInventory.ClickEvent)2 EditGUIButton (com.bencodez.advancedcore.api.inventory.editgui.EditGUIButton)2 EditGUIValueInventory (com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueInventory)2 EditGUIValueList (com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueList)2 EditGUIValueString (com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueString)2 ItemBuilder (com.bencodez.advancedcore.api.item.ItemBuilder)2 RewardEditAdvancedRandomReward (com.bencodez.advancedcore.api.rewards.editbuttons.RewardEditAdvancedRandomReward)2 RewardInjectConfigurationSection (com.bencodez.advancedcore.api.rewards.injected.RewardInjectConfigurationSection)2 RewardInjectString (com.bencodez.advancedcore.api.rewards.injected.RewardInjectString)2 RequirementInjectConfigurationSection (com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectConfigurationSection)2 RequirementInjectDouble (com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectDouble)2 RequirementInjectString (com.bencodez.advancedcore.api.rewards.injectedrequirement.RequirementInjectString)2 AdvancedCoreUser (com.bencodez.advancedcore.api.user.AdvancedCoreUser)2 ArrayList (java.util.ArrayList)2 Player (org.bukkit.entity.Player)2 CommandHandler (com.bencodez.advancedcore.api.command.CommandHandler)1 EditGUIValueBoolean (com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueBoolean)1 EditGUIValueNumber (com.bencodez.advancedcore.api.inventory.editgui.valuetypes.EditGUIValueNumber)1