/*
 *   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.towerrun.TowerRun;
import de.steamwar.towerrun.config.Config;
import de.steamwar.towerrun.game.TowerRunGame;
import de.steamwar.towerrun.state.GameStates;

import java.util.EnumSet;

@Linked
public class GameCountdown extends Countdown {

    private long startTime = 0;

    public GameCountdown() {
        super(EnumSet.of(GameStates.RUNNING));
    }

    @Override
    int defaultTime() {
        return Config.GAME_TIMER;
    }

    @Override
    void timerEnd() {
        if (TowerRunGame.PLAYERS_ESCAPED.isEmpty()) {
            TowerRunGame.tie();
        } else {
            TowerRunGame.win(TowerRunGame.PLAYERS_ESCAPED.get(TowerRunGame.PLAYERS_ESCAPED.size() - 1));
        }
    }

    @Override
    boolean timerShouldCancel() {
        return false;
    }

    @Override
    void run() {
        int timeMinutes = Math.floorDiv(time, 60);
        int timeSeconds = time % 60;

        TowerRun.getMessage().broadcastActionbar("GAME_TIME", String.format("%02d", timeMinutes), String.format("%02d", timeSeconds));
    }

    @Override
    public void enable() {
        super.enable();
        startTime = System.currentTimeMillis();
    }

    @Override
    public void disable() {
        super.disable();
        setTime(defaultTime());
        startTime = 0;
    }

    public int getPlayTimeInSeconds() {
        if (startTime == 0) return 0;
        return (int) ((System.currentTimeMillis() - startTime) / 1000);
    }
}
