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

import de.steamwar.linkage.Linked;
import de.steamwar.linkage.LinkedInstance;
import de.steamwar.towerrun.TowerRun;
import de.steamwar.towerrun.config.Config;
import de.steamwar.towerrun.game.TowerRunGame;
import de.steamwar.towerrun.state.GameStates;
import org.bukkit.Bukkit;
import org.bukkit.Sound;

import java.util.EnumSet;
import java.util.Objects;

@Linked
public class EndCountdown extends Countdown {

    @LinkedInstance
    private LobbyCountdown lobbyCountdown;

    private static final boolean RESETS = Objects.requireNonNull(Bukkit.getWorlds().get(0).getWorldFolder().list((dir, name) -> name.equals("backup"))).length > 0;

    public EndCountdown() {
        super(EnumSet.of(GameStates.END));
    }

    @Override
    int defaultTime() {
        return 30;
    }

    @Override
    void timerEnd() {
        Bukkit.getOnlinePlayers().forEach(player -> player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_PLING, 1, 1));
        if (RESETS) {
            if (Config.event()) {
                Bukkit.shutdown();
            } else {
                TowerRunGame.reset();
            }
            lobbyCountdown.setTime(lobbyCountdown.defaultTime());
        } else {
            Bukkit.shutdown();
        }
    }

    @Override
    boolean timerShouldCancel() {
        return false;
    }

    @Override
    void run() {
        TowerRun.getMessage().broadcastActionbar(RESETS ? "SERVER_RESET" : "SERVER_STOPPING", time);
    }
}
