/*
 * 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.ModBlocks;
import com.remains_cave.dungeon.room.RoomManager;
import com.remains_cave.dungeon.room.RoomState;
import com.remains_cave.effect.ModEffects;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

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

    public EmblemBlockEntity(BlockPos pos, BlockState state) {
        super(ModBlocks.EMBLEM_BLOCK_ENTITY.get(), pos, state);
    }

    public void setRoomId(String id) { this.roomId = id; }
    public String getRoomId() { return roomId; }

    public void onStateChanged(boolean newActive) {
        if (level != null && !level.isClientSide && !roomId.isEmpty()) {
            RoomManager rm = RoomManager.get(level);
            RoomState room = rm.getOrCreateRoom(roomId);
            if (room.isEmblemActive() != newActive) {
                room.setEmblemActive(newActive);
                rm.setDirty();

                if (newActive) {
                    // 为房间内所有骷髅添加 KingsAura 效果
                    List<LivingEntity> skeletons = rm.getSkeletonsInRoom(roomId, (ServerLevel) level);
                    for (LivingEntity skeleton : skeletons) {
                        skeleton.addEffect(new MobEffectInstance(ModEffects.KINGS_AURA, -1, 0, false, false, true));
                    }
                }
            }
        }
    }

    @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");
    }

    @Override
    public @NotNull CompoundTag getUpdateTag(HolderLookup.@NotNull Provider registries) {
        CompoundTag tag = super.getUpdateTag(registries);
        tag.putString("RoomId", roomId);
        return tag;
    }

    @Nullable
    @Override
    public ClientboundBlockEntityDataPacket getUpdatePacket() {
        return ClientboundBlockEntityDataPacket.create(this);
    }
}