/*
 *   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.Event;
import de.steamwar.sql.EventFight;
import de.steamwar.sql.Team;
import de.steamwar.sql.TeamTeilnahme;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.selections.StringSelectMenu;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;

import java.awt.*;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@UtilityClass
public class EventChannel {

    public MessageCreateBuilder get() {
        if (Event.get() == null) return updateComing();

        return updateCurrent();
    }

    private MessageCreateBuilder updateComing() {
        EmbedBuilder embedBuilder = new EmbedBuilder()
                .setColor(Color.GRAY)
                .setTitle("Zukünftige Events")
                .setAuthor("SteamWar", "https://www.steamwar.de");


        StringSelectMenu.Builder menuBuilder = StringSelectMenu.create("eventName")
                .setPlaceholder("Wähle ein Event aus!")
                .setMinValues(1)
                .setMaxValues(1);

        Timestamp now = Timestamp.from(Instant.now());
        List<Event> events = Event.getComing();
        events.forEach(event -> {
            StringBuilder st = new StringBuilder();
            if (event.getDeadline().after(now)) {
                st.append("Deadline: <t:").append(event.getDeadline().getTime() / 1000).append(":R>\n");
            }
            st.append("Start: <t:").append(event.getStart().getTime() / 1000).append(":R>");
            String teilname = TeamTeilnahme.getTeams(event.getEventID()).stream().map(Team::getTeamKuerzel).collect(Collectors.joining(", "));
            if (!teilname.isEmpty()) {
                st.append("\nAngemeldete Teams: ").append(teilname);
            }
            embedBuilder.addField(event.getEventName(), st.toString(), false);
            if (event.getDeadline().after(Timestamp.from(Instant.now()))) {
                menuBuilder.addOption(event.getEventName(), event.getEventID() + "", "An " + event.getEventName() + " teilnehmen", Emoji.fromUnicode("U+1F4DD"));
            }
        });

        MessageCreateBuilder messageBuilder = new MessageCreateBuilder()
                .setEmbeds(embedBuilder.build());

        if (events.stream().anyMatch(event -> event.getDeadline().after(Timestamp.from(Instant.now())))) {
            messageBuilder.setComponents(ActionRow.of(menuBuilder.build()));
        }
        return messageBuilder;
    }

    private MessageCreateBuilder updateCurrent() {
        Event event = Event.get();
        EmbedBuilder embedBuilder = new EmbedBuilder()
                .setColor(Color.GRAY)
                .setTitle("Event: " + event.getEventName())
                .setAuthor("SteamWar", "https://www.steamwar.de");

        Instant now = Instant.now();
        EventFight.getEvent(event.getEventID()).forEach(eventFight -> {
            Team teamBlue = Team.byId(eventFight.getTeamBlue());
            Team teamRed = Team.byId(eventFight.getTeamRed());

            if (eventFight.getStartTime().toLocalDateTime().getDayOfYear() != LocalDate.now().getDayOfYear()) {
                return;
            }

            StringBuilder st = new StringBuilder();
            st.append("Fightbeginn: <t:").append(eventFight.getStartTime().getTime() / 1000).append(":R>");
            if (now.isAfter(eventFight.getStartTime().toInstant().plus(35, ChronoUnit.MINUTES))) {
                st.append("\n");
                if (eventFight.getErgebnis() == 1) {
                    st.append("Sieg ").append(teamBlue.getTeamKuerzel());
                } else if (eventFight.getErgebnis() == 2) {
                    st.append("Sieg ").append(teamRed.getTeamKuerzel());
                } else {
                    st.append("Unentschieden");
                }
            }
            embedBuilder.addField(teamBlue.getTeamKuerzel() + " vs. " + teamRed.getTeamKuerzel(), st.toString(), true);
        });

        return StaticMessageChannel.toMessageBuilder(embedBuilder);
    }

}
