/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2020  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.sql;

import de.steamwar.sql.internal.Field;
import de.steamwar.sql.internal.SelectStatement;
import de.steamwar.sql.internal.Statement;
import de.steamwar.sql.internal.Table;
import lombok.AllArgsConstructor;

import java.util.Set;
import java.util.stream.Collectors;

@AllArgsConstructor
public class TeamTeilnahme {

    private static final Table<TeamTeilnahme> table = new Table<>(TeamTeilnahme.class);
    private static final SelectStatement<TeamTeilnahme> select = table.select(Table.PRIMARY);
    private static final SelectStatement<TeamTeilnahme> selectTeams = table.selectFields("EventID");
    private static final SelectStatement<TeamTeilnahme> selectEvents = table.selectFields("TeamID");
    private static final Statement insert = table.insert(Table.PRIMARY);
    private static final Statement delete = table.delete(Table.PRIMARY);
    private static final Statement deleteFuture = new Statement("DELETE t FROM TeamTeilnahme t INNER JOIN Event e ON t.EventID = e.EventID WHERE t.TeamID = ? AND e.Start > NOW()");

    @Field(keys = {Table.PRIMARY})
    private final int teamId;
    @Field(keys = {Table.PRIMARY})
    private final int eventId;

    public static boolean nimmtTeil(int teamID, int eventID){
        return select.select(teamID, eventID) != null;
    }

    public static void teilnehmen(int teamID, int eventID){
        insert.update(teamID, eventID);
    }

    public static void notTeilnehmen(int teamID, int eventID){
        delete.update(teamID, eventID);
    }

    public static void deleteFuture(int teamID) {
        deleteFuture.update(teamID);
    }

    public static Set<Team> getTeams(int eventID){
        return selectTeams.listSelect(eventID).stream().map(tt -> Team.get(tt.teamId)).collect(Collectors.toSet()); // suboptimal performance (O(n) database queries)
    }

    public static Set<Event> getEvents(int teamID){
        return selectEvents.listSelect(teamID).stream().map(tt -> Event.get(tt.eventId)).collect(Collectors.toSet()); // suboptimal performance (O(n) database queries)
    }
}
