Volver al índice

src/main/java/ar/com/companeros/panel/client/RapsSettingsScreen.java

package ar.com.companeros.panel.client;

import ar.com.companeros.horror.client.HorrorClientSafety;
import ar.com.companeros.panel.*;
import com.google.gson.*;
import java.util.*;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.*;
import net.minecraft.client.gui.screens.*;
import net.minecraft.network.chat.Component;

/** Preferencia personal y operaciones administrativas confirmadas por el servidor. */
public final class RapsSettingsScreen extends Screen {
    private final Screen parent;
    private JsonObject state = new JsonObject();
    private final List<Row> rows = new ArrayList<>();
    private final List<Label> labels = new ArrayList<>();
    private int tab, page, pendingId;
    private static int serial;
    private long sentAt;
    private boolean requested;
    private String message = "", selectedBot = "";
    private int left, panelWidth, visibleRows, totalPages;
    private interface Row { void build(int x, int y, int width); }
    private record Label(String text, int x, int y, int color) { }
    public RapsSettingsScreen(Screen parent) { super(Component.literal("Raps")); this.parent = parent; }
    private boolean connected() {
        return minecraft != null && minecraft.getConnection() != null && PanelNetwork.present(minecraft.getConnection().getConnection());
    }
    private boolean ready() { return connected() && pendingId == 0 && state.has("admin"); }
    private boolean admin() { return state.has("admin") && state.get("admin").getAsBoolean(); }
    private boolean flag(JsonObject object, String key) { return object.has(key) && object.get(key).getAsBoolean(); }
    private JsonObject horror() { return state.has("horror") ? state.getAsJsonObject("horror") : new JsonObject(); }
    private JsonObject api() { return state.has("api") ? state.getAsJsonObject("api") : new JsonObject(); }
    private int number(JsonObject object, String key, int fallback) { return object.has(key) ? object.get(key).getAsInt() : fallback; }
    private String text(JsonObject object, String key, String fallback) { return object.has(key) ? object.get(key).getAsString() : fallback; }

    // El servidor responde a la instancia y solicitud que todavía están abiertas.
    public static void receive(PanelNetwork.Response response) {
        if (!(Minecraft.getInstance().screen instanceof RapsSettingsScreen screen) || response.id() != screen.pendingId) return;
        screen.pendingId = 0;
        try {
            screen.state = JsonParser.parseString(response.json()).getAsJsonObject();
            screen.message = screen.text(screen.state, "message", "");
            PanelSoundMix.apply(screen.number(screen.state, "volume", 100));
        } catch (RuntimeException invalid) { screen.message = "No se pudo leer el estado del servidor."; }
        screen.rebuild();
    }
    private void send(PanelPolicy.Action action, String value) {
        if (!connected() || pendingId != 0) return;
        pendingId = ++serial; sentAt = Util.getMillis(); message = "";
        PanelNetwork.request(pendingId, action, value); rebuild();
    }
    @Override protected void init() {
        rebuild();
        if (!requested && connected()) { requested = true; send(PanelPolicy.Action.STATUS, ""); }
    }
    @Override public void tick() {
        for (var child : children()) if (child instanceof EditBox box) box.tick();
        if (pendingId != 0 && Util.getMillis() - sentAt > 8000) {
            pendingId = 0; message = "El servidor no respondió. Podés actualizar e intentar de nuevo."; rebuild();
        }
    }
    @Override public boolean isPauseScreen() { return false; }
    @Override public void onClose() { minecraft.setScreen(parent); }

    // Las páginas mantienen controles completos incluso con escala de GUI alta.
    private void rebuild() {
        if (minecraft == null) return;
        clearWidgets(); rows.clear(); labels.clear();
        panelWidth = PanelLayout.panelWidth(width); left = (width - panelWidth) / 2;
        visibleRows = PanelLayout.rows(height);
        String[] tabs = admin() ? new String[]{"Personal", "Bots", "Huésped", "API"} : new String[]{"Personal"};
        if (tab >= tabs.length) { tab = 0; page = 0; }
        int tabWidth = (panelWidth - (tabs.length - 1) * 4) / tabs.length;
        for (int i = 0; i < tabs.length; i++) {
            final int target = i;
            var button = addRenderableWidget(Button.builder(Component.literal(tabs[i]), b -> { tab = target; page = 0; message = ""; rebuild(); })
                .bounds(left + i * (tabWidth + 4), 38, tabWidth, 20).build());
            button.active = i != tab;
        }
        switch (tab) { case 0 -> personal(); case 1 -> bots(); case 2 -> creature(); case 3 -> provider(); default -> { } }
        totalPages = Math.max(1, (rows.size() + visibleRows - 1) / visibleRows);
        page = Math.max(0, Math.min(page, totalPages - 1));
        for (int i = 0; i < visibleRows && page * visibleRows + i < rows.size(); i++) rows.get(page * visibleRows + i).build(left, 72 + i * 34, panelWidth);
        var previous = addRenderableWidget(Button.builder(Component.literal("<"), b -> { page--; rebuild(); }).bounds(left, height - 26, 24, 20).build());
        previous.active = page > 0; previous.visible = totalPages > 1;
        var next = addRenderableWidget(Button.builder(Component.literal(">"), b -> { page++; rebuild(); }).bounds(left + 62, height - 26, 24, 20).build());
        next.active = page + 1 < totalPages; next.visible = totalPages > 1;
        var refresh = addRenderableWidget(Button.builder(Component.literal("Actualizar"), b -> send(PanelPolicy.Action.STATUS, ""))
            .bounds(left + panelWidth - 178, height - 26, 86, 20).build());
        refresh.active = connected() && pendingId == 0;
        addRenderableWidget(Button.builder(Component.literal("Volver"), b -> onClose()).bounds(left + panelWidth - 86, height - 26, 86, 20).build());
    }
    private void personal() {
        rows.add((x, y, w) -> {
            boolean enabled = state.has("sensitive") ? flag(state, "sensitive") : HorrorClientSafety.isEnabled();
            var checkbox = addRenderableWidget(new Checkbox(x, y + 6, w, 20, Component.literal("Modo seguro"), enabled) {
                @Override public void onPress() { if (active) send(PanelPolicy.Action.SENSITIVITY, Boolean.toString(!selected())); }
            });
            checkbox.active = ready();
            checkbox.setTooltip(Tooltip.create(Component.literal("La criatura te ignora y se muestra con su aspecto amigable.")));
        });
        line("La criatura no te atacará mientras esté activado.");
        line("El sonido se regula en Criaturas hostiles.");
        if (!connected()) line(minecraft.player == null ? "Entrá a un mundo para cambiar el modo seguro." : "Este servidor no tiene el panel de Raps.");
    }
    private List<JsonObject> botList() {
        List<JsonObject> result = new ArrayList<>();
        if (state.has("bots")) for (JsonElement bot : state.getAsJsonArray("bots")) result.add(bot.getAsJsonObject());
        return result;
    }
    private JsonObject selected() {
        List<JsonObject> bots = botList();
        JsonObject match = bots.stream().filter(bot -> text(bot, "name", "").equals(selectedBot)).findFirst().orElse(bots.isEmpty() ? new JsonObject() : bots.get(0));
        selectedBot = text(match, "name", ""); return match;
    }
    private void chooseBot() {
        JsonObject current = selected();
        rows.add((x, y, w) -> {
            labels.add(new Label("Bot", x, y, 0xB6C3D3));
            var selector = addRenderableWidget(Button.builder(Component.literal(selectedBot.isEmpty() ? "Sin bots registrados" : selectedBot), b -> {
                List<JsonObject> available = botList();
                for (int i = 0; i < available.size(); i++) if (text(available.get(i), "name", "").equals(selectedBot)) {
                    selectedBot = text(available.get((i + 1) % available.size()), "name", ""); break;
                }
                rebuild();
            }).bounds(x, y + 11, w, 20).build());
            selector.active = ready() && botList().size() > 1;
        });
        if (current.has("name")) line(flag(current, "infected") ? "Huésped infectado" : flag(current, "online") ? "Conectado" : "Desconectado");
    }
    private void bots() {
        chooseBot(); JsonObject bot = selected();
        boolean usable = !selectedBot.isEmpty() && !flag(bot, "infected");
        boolean apiReady = text(api(), "apiReason", "NO_CREDENTIAL").isEmpty();
        actionPair("Conexión", "Unir elegido", PanelPolicy.Action.JOIN_BOT, selectedBot, usable && !flag(bot, "online") && apiReady,
            "Pausar elegido", PanelPolicy.Action.PAUSE_BOT, selectedBot, usable && flag(bot, "online"));
        action("Unir todos", PanelPolicy.Action.JOIN_ALL, "", apiReady, "Las conexiones se hacen de forma escalonada.");
        action("Activar autonomía del elegido", PanelPolicy.Action.AUTONOMOUS, selectedBot, usable && flag(bot, "online") && apiReady, "Permite decidir a la IA del bot conectado.");
        numeric("Población máxima", number(api(), "population", 2), 2, 10, value -> Set.of(2, 4, 6, 10).contains(value), PanelPolicy.Action.POPULATION, true, new int[]{2,4,6,10});
    }
    private void creature() {
        JsonObject data = horror(); int stage = number(data, "stage", 0);
        line(flag(data, "active") ? "Huésped: " + text(data, "host", "") + " · Fase " + stage : "Todavía no hay un huésped.");
        numeric("Intensidad (%)", number(data, "intensity", 35), 0, 100, value -> true, PanelPolicy.Action.INTENSITY, true, null);
        numeric("Volumen del huésped (%)", number(state, "volume", 100), 0, 300, value -> true, PanelPolicy.Action.SOUND_VOLUME, true, null);
        rows.add((x, y, w) -> {
            labels.add(new Label("Eventos", x, y, 0xB6C3D3));
            var meteor = addRenderableWidget(Button.builder(Component.literal("Meteorito"), b -> confirm(PanelPolicy.Action.METEOR, "", "¿Hacer caer el meteorito?", "Esto colocará bloques en el mundo."))
                .bounds(x, y + 11, (w - 6) / 2, 20).build());
            meteor.active = ready() && !flag(data, "meteor");
            var infect = addRenderableWidget(Button.builder(Component.literal("Infectar al azar"), b -> confirm(PanelPolicy.Action.INFECT, "", "¿Infectar un bot?", "La infección transformará a un único bot y guardará sus pertenencias."))
                .bounds(x + (w + 6) / 2, y + 11, (w - 6) / 2, 20).build());
            infect.active = ready() && !flag(data, "active") && !botList().isEmpty();
        });
        if (!flag(data, "active") && !botList().isEmpty()) {
            chooseBot();
            rows.add((x, y, w) -> {
                String target = selectedBot;
                var infect = addRenderableWidget(Button.builder(Component.literal("Infectar a " + target), b -> confirm(PanelPolicy.Action.INFECT, target,
                    "¿Infectar a " + target + "?", "La infección transformará a este bot y guardará sus pertenencias."))
                    .bounds(x, y + 8, w, 20).build());
                infect.active = ready() && !target.isEmpty();
            });
        }
        numeric("Fase de mutación", stage, stage, 4, value -> true, PanelPolicy.Action.STAGE, flag(data, "active") && stage < 4, null);
        action("Adelantar una fase", PanelPolicy.Action.ADVANCE, "", flag(data, "active") && stage < 4, "La mutación no retrocede.");
        action("Invocar el cuerpo", PanelPolicy.Action.SPAWN, "", flag(data, "transferred") && !flag(data, "body"), "Requiere un huésped transferido y terreno disponible.");
        actionPair("Encuentro", "Reproducir relato", PanelPolicy.Action.LORE, "", flag(data, "body") && flag(data, "eligible"),
            "Probar persecución", PanelPolicy.Action.PURSUIT, "", flag(data, "body") && flag(data, "eligible") && stage >= 2);
        action(flag(data, "steve") ? "Aspecto: Steve" : "Aspecto: skin del huésped", PanelPolicy.Action.SKIN, flag(data, "steve") ? "host" : "Steve", true, "Alterna entre Steve y la skin del bot infectado.");
    }
    private void provider() {
        String reason = text(api(), "apiReason", "NO_CREDENTIAL");
        line("API: " + switch (reason) {
            case "" -> "lista para consultar";
            case "NO_CREDENTIAL" -> "falta una credencial";
            case "ACCOUNT_NO_CREDIT" -> "cuota o saldo agotado";
            case "PROMOTION_TOKEN_LIMIT" -> "cuota de promoción agotada";
            case "PROMOTION_EXPIRED" -> "ventana de promoción finalizada";
            case "MODEL_OR_ACCOUNT_ACCESS" -> "revisar acceso de la cuenta";
            case "OPERATOR_DISABLED", "FOUNDATION_NOT_VERIFIED" -> "desactivada";
            default -> "no disponible";
        });
        if (api().has("promotionRemaining")) {
            line("Promoción restante: " + text(api(), "promotionRemaining", "0") + " / " + text(api(), "promotionLimit", "0") + " tokens");
            line("Consumo de promoción registrado por Raps.");
            line("Fin de ventana: " + text(api(), "promotionExpiresAt", ""));
        } else line("Saldo de cuenta: no consultado.");
        line("Solicitudes: " + text(api(), "calls", "0") + " · En curso: " + number(api(), "inFlight", 0) + " · En cola: " + number(api(), "queued", 0));
        line("Entrada: " + text(api(), "inputTokens", "0") + " tokens");
        line("Salida: " + text(api(), "outputTokens", "0") + " tokens");
        line("Gasto registrado: USD " + text(api(), "recordedUsd", "0"));
        int retry = number(api(), "retrySeconds", 0); if (retry > 0) line("Reintento en " + retry + " segundos.");
    }
    private void line(String text) { rows.add((x, y, w) -> labels.add(new Label(text, x, y + 10, 0xE0E7EF))); }
    private void action(String title, PanelPolicy.Action action, String value, boolean available, String tooltip) {
        rows.add((x, y, w) -> {
            var button = addRenderableWidget(Button.builder(Component.literal(title), b -> send(action, value)).bounds(x, y + 8, w, 20).build());
            button.active = ready() && available; button.setTooltip(Tooltip.create(Component.literal(tooltip)));
        });
    }
    private void actionPair(String title, String first, PanelPolicy.Action a, String av, boolean ae, String second, PanelPolicy.Action b, String bv, boolean be) {
        rows.add((x, y, w) -> {
            labels.add(new Label(title, x, y, 0xB6C3D3));
            var one = addRenderableWidget(Button.builder(Component.literal(first), button -> send(a, av)).bounds(x, y + 11, (w - 6) / 2, 20).build());
            var two = addRenderableWidget(Button.builder(Component.literal(second), button -> send(b, bv)).bounds(x + (w + 6) / 2, y + 11, (w - 6) / 2, 20).build());
            one.active = ready() && ae; two.active = ready() && be;
        });
    }
    private void confirm(PanelPolicy.Action action, String value, String title, String description) {
        minecraft.setScreen(new ConfirmScreen(accepted -> { minecraft.setScreen(this); if (accepted) send(action, value); }, Component.literal(title), Component.literal(description)));
    }

    // Barra y campo numérico sincronizados. Sólo Aplicar envía cambios al servidor.
    private void numeric(String title, int initial, int min, int max, IntPredicate allowed, PanelPolicy.Action action, boolean available, int[] steps) {
        rows.add((x, y, w) -> {
            labels.add(new Label(title, x, y, 0xB6C3D3));
            EditBox exact = new EditBox(font, x + w - 108, y + 11, 40, 20, Component.literal(title));
            exact.setMaxLength(3); exact.setFilter(value -> value.matches("[0-9]{0,3}")); exact.setValue(Integer.toString(initial));
            exact.setTooltip(Tooltip.create(Component.literal(steps == null ? "Valor exacto: " + min + " a " + max : "Valores permitidos: 2, 4, 6 o 10")));
            var apply = Button.builder(Component.literal("Aplicar"), button -> send(action, exact.getValue())).bounds(x + w - 62, y + 11, 62, 20).build();
            NumericSlider slider = new NumericSlider(x, y + 11, w - 114, min, max, initial, steps, value -> exact.setValue(Integer.toString(value)));
            exact.setResponder(value -> {
                boolean valid = false;
                try { int number = PanelPolicy.integer(value, min, max); valid = allowed.test(number); if (valid) slider.number(number); }
                catch (IllegalArgumentException ignored) { }
                exact.setTextColor(valid ? 0xFFFFFF : 0xFF7777); apply.active = ready() && available && valid;
            });
            slider.active = ready() && available; exact.active = ready() && available; apply.active = ready() && available && allowed.test(initial);
            addRenderableWidget(slider); addRenderableWidget(exact); addRenderableWidget(apply);
        });
    }
    private static final class NumericSlider extends AbstractSliderButton {
        private final int min, max; private final int[] steps; private final IntConsumer changed;
        NumericSlider(int x, int y, int width, int min, int max, int initial, int[] steps, IntConsumer changed) {
            super(x, y, width, 20, Component.empty(), (initial - min) / (double)Math.max(1, max - min));
            this.min = min; this.max = max; this.steps = steps; this.changed = changed; updateMessage();
        }
        private int number() {
            int result = min + (int)Math.round(value * (max - min));
            if (steps != null) { int closest = steps[0]; for (int step : steps) if (Math.abs(step - result) < Math.abs(closest - result)) closest = step; result = closest; }
            return result;
        }
        void number(int number) { value = (number - min) / (double)Math.max(1, max - min); updateMessage(); }
        @Override protected void updateMessage() { setMessage(Component.literal(Integer.toString(number()))); }
        @Override protected void applyValue() { int number = number(); number(number); changed.accept(number); }
    }
    @Override public boolean mouseScrolled(double x, double y, double delta) {
        if (y >= 65 && y < height - 58 && totalPages > 1) { page = Math.max(0, Math.min(totalPages - 1, page + (delta < 0 ? 1 : -1))); rebuild(); return true; }
        return super.mouseScrolled(x, y, delta);
    }
    @Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partial) {
        renderBackground(graphics);
        graphics.fill(left - 8, 6, left + panelWidth + 8, height - 3, 0xDC10151E);
        graphics.drawCenteredString(font, title, width / 2, 15, 0xFFFFFF);
        super.render(graphics, mouseX, mouseY, partial);
        for (Label label : labels) graphics.drawString(font, font.plainSubstrByWidth(label.text, panelWidth), label.x, label.y, label.color);
        if (totalPages > 1) graphics.drawCenteredString(font, (page + 1) + "/" + totalPages, left + 43, height - 20, 0xC5CDD8);
        String footer = pendingId != 0 ? "Consultando al servidor…" : message;
        var lines = font.split(Component.literal(footer), panelWidth);
        for (int i = 0; i < Math.min(2, lines.size()); i++) graphics.drawString(font, lines.get(i), left, height - 51 + i * 10, 0xD1DEEB);
        if (lines.size() > 2 && mouseX >= left && mouseX <= left + panelWidth && mouseY >= height - 54 && mouseY < height - 28)
            graphics.renderTooltip(font, Component.literal(footer), mouseX, mouseY);
    }
}