package com.alttd.webinterface.bot;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.requests.GatewayIntent;

import java.util.Optional;

@Slf4j
public class DiscordBotInstance {

    private static final DiscordBotInstance INSTANCE = new DiscordBotInstance();

    public static DiscordBotInstance getInstance() {
        return INSTANCE;
    }

    private DiscordBotInstance() {}

    private JDA jda;
    private volatile boolean ready = false;

    public JDA getJda() {
        if (jda == null) {
            String discordToken = Optional.ofNullable(System.getenv("DISCORD_TOKEN"))
                    .orElse(System.getProperty("DISCORD_TOKEN"));
            if (discordToken == null) {
                log.error("Discord token not found, put it in the DISCORD_TOKEN environment variable");
                System.exit(1);
            }
            start(discordToken);
            try {
                jda.awaitReady();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return jda;
    }

    private synchronized void start(String token) {
        if (jda != null) {
            return;
        }
        jda = JDABuilder.createDefault(token,
                GatewayIntent.GUILD_MEMBERS,
                GatewayIntent.GUILD_PRESENCES,
                GatewayIntent.GUILD_MESSAGES,
                GatewayIntent.MESSAGE_CONTENT)
                .addEventListeners(new ReadyListener(() -> {
                    ready = true;
                }))
                .build();
    }

    public boolean isReady() {
        return ready && jda != null && jda.getStatus() == JDA.Status.CONNECTED;
    }
}
