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

import de.steamwar.towerrun.TowerRun;
import de.steamwar.towerrun.config.Config;
import de.steamwar.towerrun.config.WorldConfig;
import de.steamwar.towerrun.game.TowerRunGame;
import de.steamwar.towerrun.game.TowerRunPlayer;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;

import java.util.Arrays;

public abstract class OutsideWincondition extends WinCondition {

    protected OutsideWincondition(String name) {
        super(name);
    }

    public abstract void onPlayerOutside(Player player);

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        if (event.getTo().getY() > WorldConfig.ESCAPE_HEIGHT) {
            return;
        }

        TowerRunPlayer tPlayer = TowerRunPlayer.get(event.getPlayer());
        if (!TowerRunGame.isAlive(tPlayer)) {
            return;
        }

        if (Arrays.stream(WorldConfig.REGIONS).anyMatch(region -> region.contains(event.getTo().toVector()))) {
            return;
        }

        if (event.getTo().getY() - event.getFrom().getY() != 0) {
            return;
        }

        onPlayerOutside(event.getPlayer());
    }

    protected void outside(TowerRunPlayer towerRunPlayer) {
        TowerRunGame.PLAYERS_ESCAPED.add(towerRunPlayer);
        TowerRunGame.PLAYERS_ALIVE.remove(towerRunPlayer);
        towerRunPlayer.player().setGameMode(GameMode.SPECTATOR);
        TowerRun.getMessage().broadcast("PLAYER_ESCAPE", towerRunPlayer.player().getName());
        if (TowerRunGame.PLAYERS_ESCAPED.size() == 1) {
            TowerRun.getGameCountdown().setTime(Config.GAME_ESCAPE_TIMER);
        }
    }
}
