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

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.SimpleWaterloggedBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.material.PushReaction;
import net.minecraft.world.level.pathfinder.PathComputationType;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.eroticdungeongame.content.block.blockentity.DefaultSeatBlockEntity;

import java.util.Map;

@SuppressWarnings({"deprecation", "unused"})
public abstract class AbstractSeatBlock extends Block implements ISeatBlock, SimpleWaterloggedBlock {
    public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
    public AbstractSeatBlock(BlockBehaviour.Properties properties) {
        super(properties);
        registerDefaultState(
                getStateDefinition().any()
                    .setValue(FACING, Direction.NORTH)
                    .setValue(OCCUPIED, Boolean.FALSE)
                    .setValue(FLIPPED, Boolean.FALSE)
                    .setValue(WATERLOGGED, Boolean.FALSE)
        );
        initCache();
    }

    @Override
    public void initCache() {
        Class<? extends AbstractSeatBlock> clazz = this.getClass();

        // 检查是否已有缓存
        if (!CLASS_CACHE.containsKey(clazz)) {
            synchronized (clazz) {
                if (!CLASS_CACHE.containsKey(clazz)) {
                    // 创建新缓存
                    setupShape();
                }
            }
        }
    }

    @Override
    public Map<Direction, VoxelShape> getShapeCacheMap(Object key) {
        Map<?, Map<Direction, VoxelShape>> map = CLASS_CACHE.get(this.getClass());
        if (map != null) return map.get(key);
        else return null;
    }

    @Override
    public void reloadShapesCache() {
        Class<? extends AbstractSeatBlock> clazz = this.getClass();
        synchronized (clazz) {
           setupShape();
        }
    }

    @Override
    public abstract void setupShape();

    @Override
    public void setShapeCacheMap(Map<Direction, VoxelShape> shapeMap) {
        CLASS_CACHE.put(this.getClass(), Map.of(SINGLE, shapeMap));
    }

    @Override
    public @NotNull FluidState getFluidState(@NotNull BlockState state) {
        return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state);
    }

    @Override
    public BlockEntity newBlockEntity(@NotNull BlockPos blockPos, @NotNull BlockState blockState) {
        return new DefaultSeatBlockEntity(blockPos, blockState);
    }

    @Override
    public @NotNull BlockState rotate(@NotNull BlockState blockState, @NotNull Rotation rotation) {
        return blockState;
    }

    @Override
    public @NotNull BlockState mirror(@NotNull BlockState blockState, @NotNull Mirror mirror) {
        return blockState;
    }

    @Override
    public @NotNull VoxelShape getShape(@NotNull BlockState blockState, @NotNull BlockGetter blockGetter,
                               @NotNull BlockPos blockPos, @NotNull CollisionContext collisionContext) {
        Map<Direction, VoxelShape> shapes = getShapeMap();
        if (shapes != null) {
            Direction facing = blockState.getValue(FACING);
            VoxelShape shape = shapes.get(facing);
            if (shape != null) {
                return shape;
            }
        }
        return super.getShape(blockState, blockGetter, blockPos, collisionContext);
    }


    @Override
    protected void createBlockStateDefinition(StateDefinition.@NotNull Builder<Block, BlockState> builder) {
        builder.add(FACING, OCCUPIED, FLIPPED, WATERLOGGED);
    }

    @Override
    public @NotNull BlockState updateShape(@NotNull BlockState state, @NotNull Direction direction, @NotNull BlockState neighborState, @NotNull LevelAccessor level, @NotNull BlockPos pos, @NotNull BlockPos neighborPos) {
        if (state.getValue(WATERLOGGED)) {
            level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level));
        }
        return super.updateShape(state, direction, neighborState, level, pos, neighborPos);
    }

    @Override
    public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) {
        return defaultBlockState()
                .setValue(FACING, context.getHorizontalDirection().getOpposite())
                .setValue(OCCUPIED, Boolean.FALSE)
                .setValue(FLIPPED, Boolean.FALSE);
    }

    @Override
    public PushReaction getPistonPushReaction(@NotNull BlockState blockState) {
        return PushReaction.DESTROY;
    }

    @Override
    public boolean useShapeForLightOcclusion(@NotNull BlockState blockState) {
        return true;
    }


    @Override
    public boolean isSignalSource(@NotNull BlockState blockState) {
        return true;
    }

    @Override
    public int getSignal(@NotNull BlockState blockState, @NotNull BlockGetter blockGetter,
                         @NotNull BlockPos blockPos, @NotNull Direction direction) {
        return blockState.getValue(OCCUPIED) ? 15 : 0;
    }

    @Override
    @NotNull
    public InteractionResult use(@NotNull BlockState blockState, @NotNull Level level,
                                 @NotNull BlockPos blockPos, @NotNull Player player,
                                 @NotNull InteractionHand hand, @NotNull BlockHitResult hitResult) {
        return handleSeatInteraction(blockState, level, blockPos, player, hand, hitResult);
    }

    @Override
    public void onRemove(@NotNull BlockState blockState, @NotNull Level level, @NotNull BlockPos blockPos,
                         @NotNull BlockState newState, boolean moved) {
        onSeatRemoved(blockState, level, blockPos, newState, moved);
        super.onRemove(blockState, level, blockPos, newState, moved);
    }

    @Override
    public boolean isPathfindable(@NotNull BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull PathComputationType type) {
        return false;
    }
}
