/*
 *   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.commands;

import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.linkage.Linked;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Event;
import de.steamwar.sql.EventFight;
import de.steamwar.sql.Team;
import de.steamwar.sql.UserPerm;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;

@Linked
public class EventRescheduleCommand extends SWCommand {

    public EventRescheduleCommand() {
        super("eventreschedule", UserPerm.MODERATION);
    }

    @Register
    public void reschedule(Chatter sender, @Mapper("BLUE_TEAM") Team teamBlue, @Mapper("RED_TEAM") Team teamRed) {
        Event event = Event.get();
        if (event == null) {
            sender.system("EVENTRESCHEDULE_UNKNOWN_TEAM");
            return;
        }

        List<EventFight> fights = EventFight.getEvent(event.getEventID());
        ListIterator<EventFight> it = fights.listIterator(fights.size());
        Timestamp now = Timestamp.from(new Date().toInstant());
        while (it.hasPrevious()) {
            EventFight fight = it.previous();
            if (fight.getStartTime().after(now)) continue;

            if (fight.getTeamBlue() == teamBlue.getTeamId() && fight.getTeamRed() == teamRed.getTeamId()) {
                sender.system("EVENTRESCHEDULE_STARTING");
                fight.reschedule();
                EventFight.loadAllComingFights();
                return;
            }
        }

        sender.system("EVENTRESCHEDULE_NO_FIGHT");
    }

    @Mapper(value = "BLUE_TEAM", local = true)
    public TypeMapper<Team> eventBlueTeams() {
        return EventCommand.eventTeam(eventFight -> List.of(eventFight.getTeamBlue()));
    }

    @Mapper(value = "RED_TEAM", local = true)
    public TypeMapper<Team> eventRedTeams() {
        return EventCommand.eventTeam(eventFight -> List.of(eventFight.getTeamRed()));
    }
}