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

import de.steamwar.linkage.AbstractLinker;
import de.steamwar.linkage.SpigotLinker;
import de.steamwar.misslewars.items.CustomItem;
import de.steamwar.misslewars.items.Missile;
import de.steamwar.misslewars.slowmo.SlowMoRunner;
import de.steamwar.network.NetworkSender;
import de.steamwar.network.packets.common.FightEndsPacket;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.*;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

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

public class MissileWars extends JavaPlugin {
    private static MissileWars plugin;
    private static MWTeam redTeam; //red has South side -> spawns missles towards north
    private static MWTeam blueTeam;
    private static FightState fightState;

    /**
     * create teams, ect
     */
    @Override
    public void onLoad() {
        plugin = this;
        fightState = FightState.WAITING;
    }

    @Override
    public void onEnable() {
        redTeam = new MWTeam(Config.TeamRedColor, Config.RedSpawn, Config.TeamRedName, Config.RedPortalZ);
        blueTeam = new MWTeam(Config.TeamBlueColor, Config.BlueSpawn, Config.TeamBlueName, Config.BluePortalZ);

        SpigotLinker spigotLinker = new SpigotLinker(this, null) {
            @Override
            protected void linkObject(Object any) {
                // No Init needed for MissileWars!
            }
        };
        try {
            spigotLinker.link();
        } catch (AbstractLinker.LinkException e) {
            e.printStackTrace();
            Bukkit.shutdown();
            return;
        }

        Missile.init();
        CustomItem.init();

        StateDependent.setupState(fightState);

        Bukkit.getScheduler().runTaskTimer(this, new FightInfoPacketSender(), 20, 20);

        Bukkit.getWorlds().forEach(world -> {
            world.setGameRule(GameRule.KEEP_INVENTORY, true);
            world.setGameRule(GameRule.MOB_GRIEFING, true);
            world.setGameRule(GameRule.DO_TILE_DROPS, false);
        });

        // TODO: Enable Item Dropping, and the own team can pick them up! Add config value for that?
    }

    public static void waiting() {
        if (fightState == FightState.END) {
            fightState = FightState.WAITING;
            StateDependent.setupState(fightState);

            SlowMoRunner.resetSlowMoTime();

            Set<UUID> uuidList = Bukkit.getOnlinePlayers().stream().map(Entity::getUniqueId).collect(Collectors.toSet());
            if (!uuidList.contains(Config.RedLeader) || !uuidList.contains(Config.BlueLeader)) {
                Config.RedLeader = null;
                Config.BlueLeader = null;
            }

            redTeam.reset();
            blueTeam.reset();
        }
    }

    /**
     * call to change fightstate from WAITING to INGAME
     */
    static void startRound() {
        if (fightState != FightState.WAITING) // anti dual-call
            return;
        fightState = FightState.FIGHTING;
        StateDependent.setupState(fightState);
    }

    /**
     * Fight beenden
     *
     * @param reason Grund fürs ende
     * @param winner Gewinner (oder null)
     */
    public static void end(WinReasons reason, MWTeam winner) {
        if (fightState == FightState.END) //verhindern dass es mehrfach gecallt wird
            return;
        fightState = FightState.END;
        StateDependent.setupState(fightState);

        for (Player player : Bukkit.getOnlinePlayers()) {
            player.playSound(player.getLocation(), Sound.ENTITY_ENDER_DRAGON_DEATH, 100f, 1f);
            player.setGameMode(GameMode.SPECTATOR);
        }

        byte ergebnis = winner == blueTeam ? (byte) 1 : (byte) 2;
        if (Config.isEvent()) {
            Config.EventKampf.setErgebnis(ergebnis);
        }
        if (Config.isEvent() || Config.isChallenge()) {
            FightEndsPacket packet = FightEndsPacket.builder().gameMode("MissileWars").duration((int) ((System.currentTimeMillis() - FightScoreboard.getStartTime()) / 1000)).win(ergebnis).bluePlayers(blueTeam.getPlayers().stream().map(Player::getUniqueId).map(SteamwarUser::get).map(SteamwarUser::getId).collect(Collectors.toList())).redPlayers(redTeam.getPlayers().stream().map(Player::getUniqueId).map(SteamwarUser::get).map(SteamwarUser::getId).collect(Collectors.toList())).blueSchem(-1).redSchem(-1).build();
            NetworkSender.send(packet);
        }

        switch (reason) {
            case PORTAL_DESTROYED:
                Bukkit.getServer().broadcastMessage(winner.getColoredName() + ChatColor.RESET + " §7hat das gegnerische Portal zerstört");
                break;
            case NO_ENEMY:
            default:
                Bukkit.getServer().broadcastMessage("§7Team " + winner.getColoredName() + ChatColor.RESET + " §7hat aufgrund fehlenden Gegners gewonnen");
                break;
        }
    }

    public static MissileWars getPlugin() {
        return plugin;
    }

    public static FightState getFightState() {
        return fightState;
    }

    public static MWTeam getRedTeam() {
        return redTeam;
    }

    public static MWTeam getBlueTeam() {
        return blueTeam;
    }

    public static MWTeam getTeam(Player p) {
        if (blueTeam.hasPlayer(p)) return blueTeam;
        if (redTeam.hasPlayer(p)) return redTeam;
        return null;
    }

    public static MWTeam getInvitation(Player p) {
        if (blueTeam.hasInvite(p)) return blueTeam;
        if (redTeam.hasInvite(p)) return redTeam;
        return null;
    }

    public static void leave(Player p) {
        MissileWars.getBlueTeam().leave(p);
        MissileWars.getRedTeam().leave(p);
    }

}
