/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.content.util;

import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.r3944realms.eroticdungeongame.EroticDungeon;
import top.r3944realms.eroticdungeongame.content.block.AbstractSeatBlock;
import top.r3944realms.eroticdungeongame.content.block.blockentity.BaseSeatBlockEntity;
import top.r3944realms.eroticdungeongame.content.block.multiply.IHasPrimaryPart;
import top.r3944realms.eroticdungeongame.content.entity.SeatEntity;
import top.r3944realms.eroticdungeongame.core.device.ISeatType;
import top.r3944realms.eroticdungeongame.core.device.SeatType;

import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;

public class FurnitureHelper {
    private FurnitureHelper() {
        throw new UnsupportedOperationException("Utility class");
    }

    // ==================== 查询功能 ====================

    /**
     * 获取实体对应的设备ID
     */
    public static @Nullable String getEntityDeviceId(@NotNull Entity entity) {
        String encodeId = entity.getEncodeId();
        if (encodeId == null) return null;

        return encodeId.substring(EroticDungeon.MOD_ID.length() + 8); // "entity.modid."
    }

    /**
     * 根据UUID获取实体
     */
    public static Optional<Entity> getEntityByUUID(@NotNull Level level, @Nullable UUID entityId) {
        if (entityId == null || !(level instanceof ServerLevel serverLevel)) {
            return Optional.empty();
        }
        return Optional.ofNullable(serverLevel.getEntity(entityId));
    }

    /**
     * 获取座椅方块实体
     */
    public static @Nullable BaseSeatBlockEntity getSeatBlockEntity(@NotNull Level level, @NotNull BlockPos blockPos) {
        BlockState blockState = level.getBlockState(blockPos);
        BlockPos targetPos = getPrimaryPartPos(blockState, blockPos);

        return getBaseSeatBlockEntity(level, targetPos);
    }

    /**
     * 检查是否是束缚设备
     */
    public static boolean isRestraintDevice(@NotNull Block block) {
        return block instanceof AbstractSeatBlock;
    }

    /**
     * 根据方块获取座椅类型
     */
    public static @Nullable ISeatType getSeatType(@NotNull Block block) {
        return Arrays.stream(SeatType.values())
                .filter(seatType -> seatType.getBlockClass().equals(block.getClass()))
                .findFirst()
                .orElse(null);
    }

    // ==================== 方块操作功能 ====================

    /**
     * 批量设置方块状态
     */
    public static void setBlockStates(@NotNull Level level,
                                      @NotNull BooleanProperty property,
                                      boolean value,
                                      @NotNull BlockPos @NotNull ... positions) {
        for (BlockPos pos : positions) {
            setBlockState(level, pos, property, value);
        }
    }

    /**
     * 设置单个方块状态
     */
    public static void setBlockState(@NotNull Level level,
                                     @NotNull BlockPos pos,
                                     @NotNull BooleanProperty property,
                                     boolean value) {
        BlockState state = level.getBlockState(pos);
        if (state.hasProperty(property)) {
            level.setBlock(pos, state.setValue(property, value), Block.UPDATE_ALL);
        }
    }

    /**
     * 设置座椅方块状态
     */
    public static void setSeatOccupied(@NotNull Level level,
                                       @NotNull BlockPos pos,
                                       boolean occupied) {
        BlockState state = level.getBlockState(pos);
        if (state.hasProperty(AbstractSeatBlock.OCCUPIED)) {
            if (state.getBlock() instanceof IHasPrimaryPart<?> primaryPart) {
                BlockPos[] allPartPos = primaryPart.getAllPartPos(level, pos);
                setBlockStates(level, AbstractSeatBlock.OCCUPIED, occupied, allPartPos);
            } else {
                setBlockStates(level, AbstractSeatBlock.OCCUPIED, occupied, pos);
            }
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 获取主要部分的位置（用于多方块结构）
     */
    private static BlockPos getPrimaryPartPos(@NotNull BlockState state, @NotNull BlockPos pos) {
        Block block = state.getBlock();
        if (block instanceof IHasPrimaryPart<?> hasPrimaryPart) {
            return hasPrimaryPart.getPrimaryPartPos(state, pos);
        }
        return pos; // 不是多方块结构，返回原始位置
    }

    /**
     * 获取基础座椅方块实体
     */
    private static @Nullable BaseSeatBlockEntity getBaseSeatBlockEntity(@NotNull Level level,
                                                                        @NotNull BlockPos pos) {
        BlockEntity blockEntity = level.getBlockEntity(pos);
        return blockEntity instanceof BaseSeatBlockEntity seat ? seat : null;
    }

    // ==================== 新增加的功能方法 ====================

    /**
     * 检查玩家是否骑乘在座椅上
     */
    public static boolean isPlayerOnSeat(@NotNull Player player) {
        return player.isPassenger() && player.getVehicle() instanceof SeatEntity;
    }

    /**
     * 获取玩家骑乘的座椅实体
     */
    public static Optional<SeatEntity> getPlayerSeat(@NotNull Player player) {
        return player.isPassenger() && player.getVehicle() instanceof SeatEntity seat ?
                Optional.of(seat) : Optional.empty();
    }

    /**
     * 获取座椅的位置信息
     */
    public static Optional<BlockPos> getSeatBlockPos(@NotNull SeatEntity seat) {
        return Optional.ofNullable(seat.getLinkedBlockPos());
    }

    /**
     * 验证座椅是否有效
     */
    public static boolean isValidSeat(@NotNull SeatEntity seat) {
        return seat.isAlive() && seat.getLinkedBlockPos() != null;
    }
}
