Search in sources :

Example 1 with TaskManager

use of at.haha007.edenclient.utils.tasks.TaskManager in project EdenClient by HahaOO7.

the class ChestShopMod method registerCommand.

private void registerCommand(String name) {
    LiteralArgumentBuilder<ClientCommandSource> node = literal(name);
    node.then(literal("clear").executes(c -> {
        shops.clear();
        sendModMessage("Cleared ChestShop entries.");
        return 1;
    }));
    node.then(literal("updateshops").executes(c -> {
        var shops = EdenClient.getMod(DataFetcher.class).getPlayerWarps().getShops();
        TaskManager tm = new TaskManager((shops.size() + 2) * 120);
        sendModMessage(ChatColor.GOLD + "Teleporting to all player warps, this will take about " + ChatColor.AQUA + (shops.size() * 6) + ChatColor.GOLD + " seconds.");
        int count = shops.size();
        AtomicInteger i = new AtomicInteger(1);
        for (String shop : shops.keySet()) {
            tm.then(new RunnableTask(() -> PlayerUtils.messageC2S("/pw " + shop)));
            // wait for chunks to load
            tm.then(new WaitForTicksTask(120));
            tm.then(new RunnableTask(() -> sendModMessage(ChatColor.GOLD + "Shop " + ChatColor.AQUA + i.getAndIncrement() + ChatColor.GOLD + "/" + ChatColor.AQUA + count + ChatColor.GOLD + " | " + ChatColor.AQUA + ((count - i.get() + 1) * 5) + ChatColor.GOLD + " seconds left")));
            tm.then(new RunnableTask(() -> checkForShops(PlayerUtils.getPlayer(), 8)));
        }
        tm.start();
        return 1;
    }));
    node.then(literal("list").executes(c -> {
        int sum = shops.values().stream().mapToInt(Set::size).sum();
        if (sum < 20)
            shops.values().forEach(sl -> sl.stream().map(cs -> cs.getItem() + " B" + cs.getBuyPricePerItem() + ":" + cs.getSellPricePerItem() + "S").forEach(PlayerUtils::sendModMessage));
        sendModMessage(String.format("There are %s ChestShops stored.", sum));
        return 1;
    }));
    node.then(literal("toggle").executes(c -> {
        searchEnabled = !searchEnabled;
        sendModMessage("ChestShop search " + (searchEnabled ? "enabled" : "disabled"));
        return 1;
    }));
    node.then(literal("sell").then(argument("item", StringArgumentType.greedyString()).suggests(this::suggestSell).executes(c -> {
        sendModMessage("Sell: ");
        String item = EdenClient.getMod(DataFetcher.class).getChestShopItemNames().getShortName(c.getArgument("item", String.class));
        List<ChestShopEntry> matching = new ArrayList<>();
        shops.values().forEach(m -> m.stream().filter(ChestShopEntry::canSell).filter(e -> e.getItem().equals(item)).forEach(matching::add));
        matching.stream().sorted(Comparator.comparingDouble(ChestShopEntry::getSellPricePerItem).reversed()).limit(10).map(cs -> {
            Optional<Map.Entry<String, Vec3i>> opw = getNearestPlayerWarp(cs.getPos());
            Style style = Style.EMPTY.withColor(Formatting.GOLD);
            Vec3i pos = cs.getPos();
            String cmd = EdenClient.getMod(GetTo.class).getCommandTo(pos);
            Text hoverText = new LiteralText(opw.isPresent() ? opw.get().getKey() : "click me!").formatted(Formatting.GOLD);
            style = style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverText));
            style = style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmd));
            return new LiteralText(cs.formattedString(false)).setStyle(style);
        }).forEach(PlayerUtils::sendModMessage);
        return 1;
    })));
    node.then(literal("buy").then(argument("item", StringArgumentType.greedyString()).suggests(this::suggestBuy).executes(c -> {
        String item = EdenClient.getMod(DataFetcher.class).getChestShopItemNames().getShortName(c.getArgument("item", String.class));
        sendModMessage("Buy: ");
        List<ChestShopEntry> matching = new ArrayList<>();
        shops.values().forEach(m -> m.stream().filter(ChestShopEntry::canBuy).filter(e -> e.getItem().equals(item)).forEach(matching::add));
        matching.stream().sorted(Comparator.comparingDouble(ChestShopEntry::getBuyPricePerItem)).limit(10).map(cs -> {
            Optional<Map.Entry<String, Vec3i>> opw = getNearestPlayerWarp(cs.getPos());
            Style style = Style.EMPTY.withColor(Formatting.GOLD);
            Vec3i pos = cs.getPos();
            String cmd = EdenClient.getMod(GetTo.class).getCommandTo(pos);
            Text hoverText = new LiteralText(opw.isPresent() ? opw.get().getKey() : "click me!").formatted(Formatting.GOLD);
            style = style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverText));
            style = style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, cmd));
            return new LiteralText(cs.formattedString(true)).setStyle(style);
        }).forEach(PlayerUtils::sendModMessage);
        return 1;
    })));
    node.then(literal("exploitable").executes(c -> {
        List<String> exploitableItems = getExploitableShopsText();
        File folder = new File(EdenClient.getDataFolder(), "ChestShop_Exploitable");
        if (!folder.exists())
            folder.mkdirs();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
        File file = new File(folder, formatter.format(new Date()) + ".txt");
        try {
            if (!file.exists())
                if (!file.createNewFile())
                    return -1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (FileWriter writer = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(writer)) {
            for (String foundDisparity : exploitableItems) {
                bw.write(foundDisparity);
                bw.newLine();
            }
            sendModMessage(new LiteralText("Wrote file without errors. Saved at ").formatted(Formatting.GOLD).append(new LiteralText(file.getAbsolutePath()).setStyle(Style.EMPTY.withColor(Formatting.GOLD).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new LiteralText("Click to copy"))).withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, file.getAbsolutePath())))));
        } catch (IOException e) {
            sendModMessage("Error while writing file. See console for more info.");
            e.printStackTrace();
        }
        return 1;
    }));
    node.then(literal("writeshopstofile").executes(c -> {
        Map<String, List<ChestShopEntry>> buyEntries = getBuyShops();
        Map<String, List<ChestShopEntry>> sellEntries = getSellShops();
        List<String> lines = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        keys.addAll(buyEntries.keySet());
        keys.addAll(sellEntries.keySet());
        keys = keys.stream().sorted(Comparator.comparing(s -> s)).collect(Collectors.toList());
        ChestShopItemNames itemNameMap = EdenClient.getMod(DataFetcher.class).getChestShopItemNames();
        for (String key : keys) {
            List<ChestShopEntry> currentBuyEntries = buyEntries.get(key);
            if (currentBuyEntries != null)
                currentBuyEntries = currentBuyEntries.stream().sorted(Comparator.comparingDouble(ChestShopEntry::getBuyPricePerItem)).collect(Collectors.toList());
            else
                currentBuyEntries = new ArrayList<>();
            List<ChestShopEntry> currentSellEntries = sellEntries.get(key);
            if (currentSellEntries != null)
                currentSellEntries = currentSellEntries.stream().sorted(Comparator.comparingDouble(ChestShopEntry::getSellPricePerItem).reversed()).collect(Collectors.toList());
            else
                currentSellEntries = new ArrayList<>();
            String originalName = itemNameMap.getLongName(key);
            if (originalName == null)
                originalName = key;
            lines.add(originalName + ":");
            if (currentBuyEntries.size() > 0) {
                lines.add("Buy:");
                currentBuyEntries.forEach(e -> lines.add(String.format("%-15s [%6d, %3d, %6d] for %.2f$/item", e.getOwner(), e.getPos().getX(), e.getPos().getY(), e.getPos().getZ(), e.getBuyPricePerItem())));
            }
            if (currentSellEntries.size() > 0) {
                lines.add("Sell:");
                currentSellEntries.forEach(e -> lines.add(String.format("%-15s [%6d, %3d, %6d] for %.2f$/item", e.getOwner(), e.getPos().getX(), e.getPos().getY(), e.getPos().getZ(), e.getSellPricePerItem())));
            }
            lines.add("");
        }
        File folder = new File(EdenClient.getDataFolder(), "ChestShopModEntries");
        if (!folder.exists())
            folder.mkdirs();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
        Date date = new Date();
        File file = new File(folder, formatter.format(date) + ".txt");
        try {
            if (!file.exists())
                if (!file.createNewFile())
                    return -1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (FileWriter writer = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(writer)) {
            for (String line : lines) {
                if (line == null) {
                    bw.write("null:");
                    continue;
                }
                bw.write(line);
                bw.newLine();
            }
            sendModMessage(new LiteralText("Wrote file without errors. Saved at ").formatted(Formatting.GOLD).append(new LiteralText(file.getAbsolutePath()).setStyle(Style.EMPTY.withColor(Formatting.GOLD).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new LiteralText("Click to copy path"))).withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, file.getAbsolutePath())))));
        } catch (IOException e) {
            sendModMessage("Error while writing file. See console for more info.");
            e.printStackTrace();
        }
        return 1;
    }));
    node.executes(c -> {
        sendModMessage("/chestshop sell itemtype");
        sendModMessage("/chestshop buy itemtype");
        sendModMessage("/chestshop toggle");
        sendModMessage("/chestshop clear");
        sendModMessage("/chestshop list");
        return 1;
    });
    register(node, "ChestShop item find/sell/buy helper.", "Automatically stores all ChestShops in all chunks you load. You can search specific items to get their buy/sell options. Other features include automatic searching for shops which sell items cheaper than other shops buy them, writing all shops to a file and automatically updating all shops via their playerwarps.");
}
Also used : WaitForTicksTask(at.haha007.edenclient.utils.tasks.WaitForTicksTask) java.util(java.util) PerWorldConfig(at.haha007.edenclient.utils.config.PerWorldConfig) ChatColor(at.haha007.edenclient.utils.ChatColor) SimpleDateFormat(java.text.SimpleDateFormat) ChunkManager(net.minecraft.world.chunk.ChunkManager) CompletableFuture(java.util.concurrent.CompletableFuture) StringArgumentType(com.mojang.brigadier.arguments.StringArgumentType) Vec3i(net.minecraft.util.math.Vec3i) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CommandManager(at.haha007.edenclient.command.CommandManager) PlayerUtils.sendModMessage(at.haha007.edenclient.utils.PlayerUtils.sendModMessage) SignBlockEntity(net.minecraft.block.entity.SignBlockEntity) PlayerTickCallback(at.haha007.edenclient.callbacks.PlayerTickCallback) ChestShopItemNames(at.haha007.edenclient.mods.datafetcher.ChestShopItemNames) DataFetcher(at.haha007.edenclient.mods.datafetcher.DataFetcher) SuggestionsBuilder(com.mojang.brigadier.suggestion.SuggestionsBuilder) ClientCommandSource(net.minecraft.client.network.ClientCommandSource) Suggestions(com.mojang.brigadier.suggestion.Suggestions) CommandContext(com.mojang.brigadier.context.CommandContext) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) GetTo(at.haha007.edenclient.mods.GetTo) ChunkPos(net.minecraft.util.math.ChunkPos) IOException(java.io.IOException) net.minecraft.text(net.minecraft.text) Collectors(java.util.stream.Collectors) LiteralArgumentBuilder(com.mojang.brigadier.builder.LiteralArgumentBuilder) File(java.io.File) WorldChunk(net.minecraft.world.chunk.WorldChunk) RunnableTask(at.haha007.edenclient.utils.tasks.RunnableTask) EdenClient(at.haha007.edenclient.EdenClient) TaskManager(at.haha007.edenclient.utils.tasks.TaskManager) Formatting(net.minecraft.util.Formatting) ConfigSubscriber(at.haha007.edenclient.utils.config.ConfigSubscriber) ClientPlayerEntity(net.minecraft.client.network.ClientPlayerEntity) PlayerUtils(at.haha007.edenclient.utils.PlayerUtils) FileWriter(java.io.FileWriter) BufferedWriter(java.io.BufferedWriter) Vec3i(net.minecraft.util.math.Vec3i) PlayerUtils(at.haha007.edenclient.utils.PlayerUtils) ChestShopItemNames(at.haha007.edenclient.mods.datafetcher.ChestShopItemNames) IOException(java.io.IOException) WaitForTicksTask(at.haha007.edenclient.utils.tasks.WaitForTicksTask) TaskManager(at.haha007.edenclient.utils.tasks.TaskManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClientCommandSource(net.minecraft.client.network.ClientCommandSource) DataFetcher(at.haha007.edenclient.mods.datafetcher.DataFetcher) RunnableTask(at.haha007.edenclient.utils.tasks.RunnableTask) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

EdenClient (at.haha007.edenclient.EdenClient)1 PlayerTickCallback (at.haha007.edenclient.callbacks.PlayerTickCallback)1 CommandManager (at.haha007.edenclient.command.CommandManager)1 GetTo (at.haha007.edenclient.mods.GetTo)1 ChestShopItemNames (at.haha007.edenclient.mods.datafetcher.ChestShopItemNames)1 DataFetcher (at.haha007.edenclient.mods.datafetcher.DataFetcher)1 ChatColor (at.haha007.edenclient.utils.ChatColor)1 PlayerUtils (at.haha007.edenclient.utils.PlayerUtils)1 PlayerUtils.sendModMessage (at.haha007.edenclient.utils.PlayerUtils.sendModMessage)1 ConfigSubscriber (at.haha007.edenclient.utils.config.ConfigSubscriber)1 PerWorldConfig (at.haha007.edenclient.utils.config.PerWorldConfig)1 RunnableTask (at.haha007.edenclient.utils.tasks.RunnableTask)1 TaskManager (at.haha007.edenclient.utils.tasks.TaskManager)1 WaitForTicksTask (at.haha007.edenclient.utils.tasks.WaitForTicksTask)1 StringArgumentType (com.mojang.brigadier.arguments.StringArgumentType)1 LiteralArgumentBuilder (com.mojang.brigadier.builder.LiteralArgumentBuilder)1 CommandContext (com.mojang.brigadier.context.CommandContext)1 Suggestions (com.mojang.brigadier.suggestion.Suggestions)1 SuggestionsBuilder (com.mojang.brigadier.suggestion.SuggestionsBuilder)1 BufferedWriter (java.io.BufferedWriter)1