/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.velocitycore.discord.channels;

import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class InteractionReply extends DiscordChannel {

    public static void reply(IReplyCallback interaction, Consumer<InteractionReply> consumer) {
        InteractionReply reply = new InteractionReply(interaction);
        consumer.accept(reply);
        reply.submit();
    }

    private final IReplyCallback interaction;

    private boolean replied = false;
    private final List<String> messages = new ArrayList<>();

    private InteractionReply(IReplyCallback interaction) {
        super(interaction.getUser());
        this.interaction = interaction;
        interaction.deferReply(true).queue();
    }

    @Override
    public void sendMessage(Component msg) {
        if (!replied) {
            messages.add(PlainTextComponentSerializer.plainText().serialize(msg));
            return;
        }

        if (interaction.getHook().isExpired()) {
            super.sendMessage(msg);
        } else {
            interaction.getHook().sendMessage(PlainTextComponentSerializer.plainText().serialize(msg)).queue();
        }
    }

    public void submit() {
        interaction.getHook().sendMessage(String.join("\n", messages)).queue();
        replied = true;
    }
}
