/*
 *   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.core.CraftbukkitWrapper;
import net.minecraft.world.level.chunk.Chunk;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.craftbukkit.v1_20_R1.CraftWorld;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;

import java.util.function.ObjIntConsumer;

public class FightWorld {

    private static final World world = Bukkit.getWorlds().get(0);

    private static double posToChunk(int pos){
        return pos / 16.0;
    }

    private static int getMinChunkX(){
        return (int) Math.floor(posToChunk(Config.ArenaMinX));
    }

    private static int getMaxChunkX(){
        return (int) Math.ceil(posToChunk(Config.ArenaMaxX));
    }

    private static int getMinChunkZ(){
        return (int) Math.floor(posToChunk(Config.ArenaMinZ));
    }

    private static int getMaxChunkZ(){
        return (int) Math.ceil(posToChunk(Config.ArenaMaxZ));
    }

    private static void forEachChunk(ObjIntConsumer<Integer> executor) {
        for(int x = getMinChunkX(); x <= getMaxChunkX(); x++)
            for(int z = getMinChunkZ(); z <= getMaxChunkZ(); z++)
                executor.accept(x, z);
    }

    public static void resetWorld(){
        world.getEntities().stream().filter(entity -> entity.getType() != EntityType.PLAYER).forEach(Entity::remove);

        World backup = new WorldCreator(world.getName() + "/backup").createWorld();
        assert backup != null;
        forEachChunk((x, z) -> resetChunk(world, backup, x, z));
        Bukkit.unloadWorld(backup, false);
    }

    private static void resetChunk(World world, World backup, int x, int z) {
        Chunk chunk = ((CraftWorld) world).getHandle().d(x, z);
        Chunk backupChunk = ((CraftWorld) backup).getHandle().d(x, z);

        System.arraycopy(backupChunk.d(), 0, chunk.d(), 0, chunk.d().length);

        for(Player p : Bukkit.getOnlinePlayers())
            CraftbukkitWrapper.impl.sendChunk(p, x, z);
    }
}
