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

import de.steamwar.fightsystem.Config;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import org.bukkit.GameRule;
import org.bukkit.World;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.entity.Entity;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class CraftbukkitWrapper {
    public static final CraftbukkitWrapper impl = new CraftbukkitWrapper();

    protected net.minecraft.world.entity.Entity getEntity(Entity e) {
        return ((CraftEntity) e).getHandle();
    }

    public float headRotation(Entity e) {
        return getEntity(e).getYHeadRot();
    }

    public Stream<net.minecraft.world.entity.Entity> entityIterator() {
        return StreamSupport.stream(((CraftWorld) Config.world).getHandle().getEntities().getAll().spliterator(), false);
    }

    public void setupGamerule() {
        Config.world.setGameRule(GameRule.LOCATOR_BAR, false);
    }

    private LevelChunk getChunk(World world, int x, int z) {
        return ((CraftWorld) world).getHandle().getChunk(x, z);
    }

    public void resetChunk(World world, World backup, int x, int z) {
        LevelChunk worldChunk = getChunk(world, x, z);
        LevelChunk backupChunk = getChunk(backup, x, z);
        LevelChunkSection[] sections = worldChunk.getSections();
        System.arraycopy(backupChunk.getSections(), 0, sections, 0, sections.length);
        Set<BlockPos> blocks = new HashSet<>(worldChunk.blockEntities.keySet());
        blocks.stream().filter(key -> !backupChunk.blockEntities.containsKey(key)).forEach(worldChunk::removeBlockEntity);
        worldChunk.heightmaps.clear();
        worldChunk.heightmaps.putAll(backupChunk.heightmaps);
    }
}
