/*
 *   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.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.velocitycore.discord.DiscordBot;
import de.steamwar.velocitycore.discord.listeners.ChannelListener;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.Webhook;
import net.dv8tion.jda.api.entities.WebhookClient;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.events.interaction.component.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.internal.requests.IncomingWebhookClientImpl;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;

import java.util.ArrayDeque;
import java.util.Queue;


@AllArgsConstructor
public class DiscordChannel extends Chatter.PlayerlessChatter {

    public static SteamwarUser userOrPublic(User dcUser) {
        SteamwarUser user = SteamwarUser.get(dcUser.getIdLong());
        return user != null ? user : SteamwarUser.get(0);
    }

    private final Queue<Webhook> webhooks = new ArrayDeque<>();

    private final SteamwarUser user;
    @Getter
    private final MessageChannel channel;

    private final int maxNumberOfWebhooks;

    public DiscordChannel(User user) {
        this(userOrPublic(user), user.openPrivateChannel().complete(), 0);
    }

    public DiscordChannel(String channel, int maxNumberOfWebhooks) {
        this(DiscordBot.getGuild().getTextChannelById(channel), maxNumberOfWebhooks);
    }

    public DiscordChannel(MessageChannel channel, int maxNumberOfWebhooks) {
        this(SteamwarUser.get(-1), channel, maxNumberOfWebhooks);
        ChannelListener.getChannels().put(this.channel, this);

        if (channel instanceof TextChannel) {
            TextChannel textChannel = (TextChannel) channel;
            webhooks.addAll(textChannel.retrieveWebhooks().complete());
            while (webhooks.size() > maxNumberOfWebhooks) {
                webhooks.remove().delete().queue();
            }
            while (webhooks.size() < maxNumberOfWebhooks) {
                webhooks.add(textChannel.createWebhook(DiscordBot.getInstance().getJda().getSelfUser().getName()).complete());
            }
        }
    }

    public void send(String message) {
        message = message
                .replace("&", "")
                .replace("@everyone", "@\u200Beveryone")
                .replace("@here", "@\u200Bhere")
                .replaceAll("<([@#])(!?\\d+)>", "<$1\u200B$2>");

        if (maxNumberOfWebhooks > 0 && getChannel() instanceof TextChannel && message.contains("»")) {
            String[] strings = message.split("»", 2);
            String userName = strings[0];
            String sendMessage = strings[1];
            strings = userName.split(" ");

            String ingameName = strings[strings.length - 1];

            SteamwarUser user = SteamwarUser.get(ingameName);
            if (user == null) {
                send(new MessageCreateBuilder()
                        .setContent(message));
                return;
            }

            String avatarUrl;
            if (user.getDiscordId() != null) {
                avatarUrl = DiscordBot.getGuild().retrieveMemberById(user.getDiscordId()).complete().getEffectiveAvatarUrl();
            } else {
                avatarUrl = DiscordBot.getInstance().getJda().getSelfUser().getAvatarUrl();
            }

            Webhook webhook = webhooks.poll();
            webhooks.add(webhook);

            // This works as per this documentation: https://discord.com/developers/docs/resources/webhook#execute-webhook
            IncomingWebhookClientImpl webhookClient = (IncomingWebhookClientImpl) WebhookClient.createClient(DiscordBot.getInstance().getJda(), webhook.getUrl());
            webhookClient.sendRequest()
                    .setUsername(userName)
                    .setAvatarUrl(avatarUrl)
                    .setContent(sendMessage)
                    .queue();
            return;
        }

        send(new MessageCreateBuilder()
                .setContent(message));
    }

    public void send(MessageCreateBuilder builder) {
        channel.sendMessage(builder.build()).queue();
    }

    public void received(MessageReceivedEvent event) {
        event.getMessage().delete().queue();
    }

    public void received(GenericComponentInteractionCreateEvent event) {
        //ignored
    }

    @Override
    public SteamwarUser user() {
        return user;
    }

    @Override
    public boolean chatShown() {
        return true;
    }

    @Override
    public Component parse(boolean prefixed, Message message) {
        return super.parse(false, message);
    }

    @Override
    public void sendMessage(Component msg) {
        send(PlainTextComponentSerializer.plainText().serialize(msg));
    }
}
