/*
 * Decompiled with CFR 0.152.
 * 
 * Could not load the following classes:
 *  meteordevelopment.orbit.EventHandler
 */
package meteordevelopment.meteorclient.systems.modules.donut;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import meteordevelopment.meteorclient.events.world.TickEvent;
import meteordevelopment.meteorclient.gui.GuiTheme;
import meteordevelopment.meteorclient.gui.widgets.WWidget;
import meteordevelopment.meteorclient.gui.widgets.containers.WVerticalList;
import meteordevelopment.meteorclient.gui.widgets.pressable.WButton;
import meteordevelopment.meteorclient.settings.BoolSetting;
import meteordevelopment.meteorclient.settings.EnumSetting;
import meteordevelopment.meteorclient.settings.Setting;
import meteordevelopment.meteorclient.settings.SettingGroup;
import meteordevelopment.meteorclient.settings.StringSetting;
import meteordevelopment.meteorclient.systems.Systems;
import meteordevelopment.meteorclient.systems.modules.Categories;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.meteorclient.systems.notifications.MeteorNotifications;
import meteordevelopment.meteorclient.utils.render.color.Color;
import meteordevelopment.orbit.EventHandler;

public class RainNotify
extends Module {
    private final SettingGroup sgGeneral;
    private final SettingGroup sgWebhook;
    private final Setting<Boolean> sendNotifications;
    private final Setting<Mode> notificationMode;
    private final Setting<Boolean> enableWebhook;
    private final Setting<String> webhookUrl;
    private final Setting<Boolean> selfPing;
    private final Setting<String> discordId;
    private boolean wasRaining;
    private boolean wasThundering;
    private final HttpClient httpClient;

    public RainNotify() {
        super(Categories.Donut, "Rain Notify", "Notifies when it starts raining or thundering in-game.");
        this.sgGeneral = this.settings.getDefaultGroup();
        this.sgWebhook = this.settings.createGroup("Webhook");
        this.sendNotifications = this.sgGeneral.add(((BoolSetting.Builder)((BoolSetting.Builder)((BoolSetting.Builder)new BoolSetting.Builder().name("notifications")).description("Send in-game notifications when it starts raining or thundering.")).defaultValue(true)).build());
        this.notificationMode = this.sgGeneral.add(((EnumSetting.Builder)((EnumSetting.Builder)((EnumSetting.Builder)((EnumSetting.Builder)new EnumSetting.Builder().name("notification-mode")).description("The mode to use for notifications.")).defaultValue(Mode.Both)).visible(this.sendNotifications::get)).build());
        this.enableWebhook = this.sgWebhook.add(((BoolSetting.Builder)((BoolSetting.Builder)((BoolSetting.Builder)new BoolSetting.Builder().name("webhook")).description("Send webhook notifications when it starts raining or thundering.")).defaultValue(false)).build());
        this.webhookUrl = this.sgWebhook.add(((StringSetting.Builder)((StringSetting.Builder)((StringSetting.Builder)((StringSetting.Builder)new StringSetting.Builder().name("webhook-url")).description("Discord webhook URL.")).defaultValue("")).visible(this.enableWebhook::get)).build());
        this.selfPing = this.sgWebhook.add(((BoolSetting.Builder)((BoolSetting.Builder)((BoolSetting.Builder)((BoolSetting.Builder)new BoolSetting.Builder().name("self-ping")).description("Ping yourself in the webhook message.")).defaultValue(false)).visible(this.enableWebhook::get)).build());
        this.discordId = this.sgWebhook.add(((StringSetting.Builder)((StringSetting.Builder)((StringSetting.Builder)((StringSetting.Builder)new StringSetting.Builder().name("discord-id")).description("Your Discord user ID for pinging.")).defaultValue("")).visible(() -> this.enableWebhook.get() != false && this.selfPing.get() != false)).build());
        this.wasRaining = false;
        this.wasThundering = false;
        this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10L)).build();
    }

    @EventHandler
    private void onTick(TickEvent.Post event) {
        if (this.mc.field_1687 == null) {
            return;
        }
        boolean raining = this.mc.field_1687.method_8419();
        boolean thundering = this.mc.field_1687.method_8546();
        if (raining && !this.wasRaining && !thundering) {
            this.notifyRainStart(false);
        }
        if (thundering && !this.wasThundering) {
            this.notifyRainStart(true);
        }
        this.wasRaining = raining;
        this.wasThundering = thundering;
    }

    private void notifyRainStart(boolean thunder) {
        if (this.sendNotifications.get().booleanValue()) {
            switch (this.notificationMode.get().ordinal()) {
                case 0: {
                    this.info("It has started " + (thunder ? "thundering!" : "raining!"), new Object[0]);
                    break;
                }
                case 1: {
                    this.showToast(thunder);
                    break;
                }
                case 2: {
                    this.info("It has started " + (thunder ? "thundering!" : "raining!"), new Object[0]);
                    this.showToast(thunder);
                }
            }
        }
        if (this.enableWebhook.get().booleanValue()) {
            this.sendWebhookNotification(thunder);
        }
    }

    private void showToast(boolean thunder) {
        Systems.get(MeteorNotifications.class).add("Weather Alert", thunder ? "The thunderstorm started!" : "The rain started!", null, new Color(120, 180, 255));
    }

    private void sendWebhookNotification(boolean thunder) {
        String url = this.webhookUrl.get().trim();
        if (url.isEmpty()) {
            this.warning("Webhook URL not configured!", new Object[0]);
            return;
        }
        CompletableFuture.runAsync(() -> {
            try {
                Object messageContent = "";
                if (this.selfPing.get().booleanValue() && !this.discordId.get().trim().isEmpty()) {
                    messageContent = "<@" + this.discordId.get().trim() + ">";
                }
                String serverInfo = this.mc.method_1558() != null ? this.mc.method_1558().field_3761 : "Singleplayer";
                String payload = String.format("{\"content\":\"%s\",\"username\":\"RainNoti\",\"embeds\":[{\"title\":\"%s Started!\",\"description\":\"It has started %s in-game.\",\"color\":3447003,\"fields\":[{\"name\":\"Server\",\"value\":\"%s\",\"inline\":true},{\"name\":\"Time\",\"value\":\"<t:%d:R>\",\"inline\":true}],\"footer\":{\"text\":\"RainNoti\"}}]}", messageContent, thunder ? "Thunderstorm" : "Rain", thunder ? "thundering" : "raining", serverInfo, System.currentTimeMillis() / 1000L);
                HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(payload)).timeout(Duration.ofSeconds(30L)).build();
                HttpResponse<String> response = this.httpClient.send(request, HttpResponse.BodyHandlers.ofString());
                if (response.statusCode() == 204) {
                    this.info("Webhook notification sent successfully", new Object[0]);
                } else {
                    this.error("Webhook failed with status: " + response.statusCode(), new Object[0]);
                }
            }
            catch (Exception e) {
                this.error("Failed to send webhook: " + e.getMessage(), new Object[0]);
            }
        });
    }

    @Override
    public WWidget getWidget(GuiTheme theme) {
        WVerticalList list = theme.verticalList();
        WButton reset = list.add(theme.button("Reset Weather State")).widget();
        reset.action = () -> {
            this.wasRaining = false;
            this.wasThundering = false;
            this.info("Weather state reset.", new Object[0]);
        };
        return list;
    }

    public static enum Mode {
        Chat,
        Toast,
        Both;

    }
}

