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

import lombok.Getter;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.world.level.block.state.BlockState;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.entity.EntityType;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * !! This class cannot be used in Versions lower than or equal to 1.19.4 !!
 */
@Getter
public class RBlockDisplay extends RDisplay {

    public static final BlockData DEFAULT_BLOCK = Material.AIR.createBlockData();

    private BlockData block;

    public RBlockDisplay(REntityServer server, Location location) {
        super(server, EntityType.BLOCK_DISPLAY, location);
        this.block = DEFAULT_BLOCK;
        server.addEntity(this);
    }

    @Override
    protected void postSpawn(Consumer<Object> packetSink) {
        super.postSpawn(packetSink);
        sendPacket(packetSink, this::getBlock);
    }

    public void setBlock(BlockData block) {
        this.block = block;
        sendPacket(updatePacketSink, this::getBlock);
    }

    private static final EntityDataAccessor<BlockState> blockWatcher = new EntityDataAccessor<>(23, EntityDataSerializers.BLOCK_STATE);

    private void getBlock(boolean ignoreDefault, EntityDataPacketBuilder packetSink) {
        if (ignoreDefault || !block.getAsString(true).equals(DEFAULT_BLOCK.getAsString(true))) {
            packetSink.add(blockWatcher, ((CraftBlockData) block).getState());
        }
    }
}
