/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.block.entity;

import com.remains_cave.block.ChallengeCageBlock;
import com.remains_cave.block.ModBlocks;
import com.remains_cave.dungeon.room.RoomManager;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;

public class ChallengeCageBlockEntity extends BlockEntity {
    private String roomId = "";

    public ChallengeCageBlockEntity(BlockPos pos, BlockState state) {
        super(ModBlocks.CHALLENGE_CAGE_BE.get(), pos, state);
    }

    public String getRoomId() {
        return roomId;
    }

    public void setRoomId(String roomId) {
        this.roomId = roomId;
        setChanged();
    }

    @Override
    protected void saveAdditional(@NotNull CompoundTag tag, HolderLookup.@NotNull Provider registries) {
        super.saveAdditional(tag, registries);
        tag.putString("RoomId", roomId);
    }

    @Override
    protected void loadAdditional(@NotNull CompoundTag tag, HolderLookup.@NotNull Provider registries) {
        super.loadAdditional(tag, registries);
        roomId = tag.getString("RoomId");
        // 服务端加载时注册到房间管理器
        if (level != null && !level.isClientSide && !roomId.isEmpty()) {
            // 根据方块状态判断是精英还是普通
            BlockState state = getBlockState();
            boolean elite = state.getValue(ChallengeCageBlock.IS_ELITE);
            if (elite) {
                RoomManager.get(level).registerEliteSpawner(roomId, worldPosition);
            } else {
                RoomManager.get(level).registerNormalSpawner(roomId, worldPosition);
            }
        }
    }

    @Override
    public void setRemoved() {
        super.setRemoved();
        if (level != null && !level.isClientSide && !roomId.isEmpty()) {
            BlockState state = getBlockState();
            boolean elite = state.getValue(ChallengeCageBlock.IS_ELITE);
            if (elite) {
                RoomManager.get(level).unregisterEliteSpawner(roomId, worldPosition);
            } else {
                RoomManager.get(level).unregisterNormalSpawner(roomId, worldPosition);
            }
        }
    }
}