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

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluids;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.eroticdungeongame.content.block.multiply.AbstractTwoPartSeatBlock;
import top.r3944realms.eroticdungeongame.content.block.part.SeatPart;

/**
 * 垂直方向的双格座椅方块
 * 两个部件在垂直方向上下堆叠
 */
public abstract class VerticalDoubleSeatBlock extends AbstractTwoPartSeatBlock {

    public VerticalDoubleSeatBlock(Properties properties) {
        super(properties);
    }

    @Override
    protected BlockPos getSecondaryPartPos(BlockPos primaryPos, Direction facing, SeatPart currentPart) {
        if (isPrimary(currentPart)) {
            // 主部件的从部件在上方
            return primaryPos.above();
        } else {
            // 从部件的主部件在下方
            return primaryPos.below();
        }
    }

    @Override
    protected void placeSecondaryPart(@NotNull Level level, BlockPos primaryPos, @NotNull BlockState primaryState,
                                      LivingEntity placer, ItemStack stack) {
        BlockPos secondaryPos = getSecondaryPartPos(primaryPos, primaryState.getValue(FACING), getPrimaryPart());

        if (level.getBlockState(secondaryPos).canBeReplaced()) {
            BlockState secondaryState = setSecondaryState(primaryState).setValue(WATERLOGGED, level.getFluidState(secondaryPos).getType() == Fluids.WATER);;
            level.setBlock(secondaryPos, secondaryState, Block.UPDATE_ALL);
            level.blockUpdated(primaryPos, Blocks.AIR);
            primaryState.updateNeighbourShapes(level, primaryPos, Block.UPDATE_ALL);
        }
    }

    @Override
    public BlockPos getPrimaryPartPos(BlockState blockState, BlockPos blockPos) {
        if (!isPrimary(blockState)) {
            // 如果点击的是从部件（上部），找到主部件位置（下部）
            return blockPos.below();
        }
        return blockPos;
    }

    @Override
    protected void handleSecondaryPartRemoval(Level level, BlockPos blockPos, BlockState blockState) {
        BlockPos otherPartPos;
        if (isPrimary(blockState)) {
            // 移除主部件（下部）时移除从部件（上部）
            otherPartPos = blockPos.above();
        } else {
            // 移除从部件（上部）时移除主部件（下部）
            otherPartPos = blockPos.below();
        }

        BlockState otherState = level.getBlockState(otherPartPos);
        if (otherState.getBlock() == this) {
            level.removeBlock(otherPartPos, false);
        }
    }

    @Override
    public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) {
        BlockPos pos = context.getClickedPos();
        BlockPos abovePos = pos.above();
        Level level = context.getLevel();
        Direction direction = context.getHorizontalDirection();

        // 检查上方位置是否可以放置
        if (level.getBlockState(abovePos).canBeReplaced(context) &&
                level.getWorldBorder().isWithinBounds(abovePos)) {

            return setPrimaryStatePart(
                    this.defaultBlockState()
                        .setValue(FACING, direction)
            );
        }
        return null;
    }

    /**
     * 检查生存条件
     */
    @Override
    public boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader level, @NotNull BlockPos pos) {
        if (isPrimary(state)) {
            // 主部件需要检查上方
            return level.getBlockState(pos.above()).canBeReplaced() &&
                    super.canSurvive(state, level, pos);
        } else {
            // 从部件需要检查下方是否有主部件
            return level.getBlockState(pos.below()).getBlock() == this &&
                    super.canSurvive(state, level, pos);
        }
    }
}
