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

import de.steamwar.fightsystem.Config;
import de.steamwar.fightsystem.FightSystem;
import de.steamwar.fightsystem.events.BoardingEvent;
import de.steamwar.fightsystem.fight.Fight;
import de.steamwar.fightsystem.fight.FightPlayer;
import de.steamwar.fightsystem.utils.Message;
import de.steamwar.fightsystem.utils.Region;
import de.steamwar.fightsystem.utils.SWSound;
import net.md_5.bungee.api.ChatMessageType;
import org.bukkit.Bukkit;

public class EnternCountdown extends Countdown {

    private static int calcTime(FightPlayer fp, Countdown countdown) {
        int time = Config.GameModeConfig.EnterStages.get(fp.getKit().getEnterStage());

        if (countdown != null) {
            time -= Config.GameModeConfig.WinConditionParams.TimeoutTime - countdown.getTimeLeft();
            if (time < 0) time = 0;
        }

        return time;
    }

    private final FightPlayer fightPlayer;

    public EnternCountdown(FightPlayer fp, Countdown countdown) {
        super(calcTime(fp, countdown), new Message("ENTERN_COUNTDOWN"), SWSound.BLOCK_NOTE_PLING, false);
        fightPlayer = fp;
        enable();
    }

    @Override
    public void countdownFinished() {
        Bukkit.getPluginManager().callEvent(new BoardingEvent(fightPlayer));
        FightSystem.getMessage().sendPrefixless("ENTERN_ALLOWED", fightPlayer.getEntity(), ChatMessageType.ACTION_BAR);
        fightPlayer.ifPlayer(player -> {
            FightSystem.getHullHider().updatePlayer(player);
            FightSystem.getTechHider().reloadChunks(player, Fight.getOpposite(fightPlayer.getTeam()).getExtendRegion(), Region.EMPTY);
        });
    }

    @Override
    protected void broadcast(String message, int divisor) {
        fightPlayer.ifPlayer(player -> {
            player.playSound(player.getLocation(), sound, 100.0f, 1.0f);
            sendCountdownMessage(player, message, time / divisor, appendix);
        });
    }
}
