/*
 *   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 de.steamwar.sql.SteamwarUser;
import de.steamwar.velocitycore.discord.DiscordBot;
import it.unimi.dsi.fastutil.Pair;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;

import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

public class CouncilChannel extends StaticMessageChannel {

    private static final Set<CouncilChannel> channels = new HashSet<>();

    public static void updateAll() {
        channels.forEach(StaticMessageChannel::update);
    }

    public CouncilChannel(Role role, ThreadChannel threadChannel) {
        super(threadChannel, () -> {
            MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder();
            messageCreateBuilder.setContent("# Ratsmitglieder");

            DiscordBot.getGuild().findMembersWithRoles(role).get()
                    .stream()
                    .map(member -> {
                        SteamwarUser steamwarUser = SteamwarUser.get(member.getIdLong());
                        String name = steamwarUser == null ? member.getEffectiveName() : steamwarUser.getUserName();
                        UUID uuid = steamwarUser == null ? null : steamwarUser.getUUID();
                        return Pair.of(name, uuid);
                    })
                    .sorted(Comparator.comparing(Pair::key))
                    .forEach(pair -> {
                        messageCreateBuilder.addEmbeds(new EmbedBuilder()
                                .setTitle(pair.key())
                                .setImage(pair.value() == null ? null : "https://api.steamwar.de/data/skin/" + pair.value().toString())
                                .build());
                    });

            return messageCreateBuilder;
        }, event -> {});

        channels.add(this);
    }
}
