/*
 * SPDX-FileCopyrightText: 2026 KOKA99CAB
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

package net.koka99cab.portals.portal;

import java.util.Optional;

import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.ItemStack;

public final class PortalIgnitionHandler {
	private PortalIgnitionHandler() {
	}

	public static void register() {
		UseBlockCallback.EVENT.register((player, level, hand, hitResult) -> {
			ItemStack stack = player.getItemInHand(hand);
			BlockPos clickedPos = hitResult.getBlockPos();

			Optional<PortalDefinition> definition = PortalDefinitions.find(stack.getItem(), level.getBlockState(clickedPos));

			if (definition.isEmpty()) {
				return InteractionResult.PASS;
			}

			BlockPos interiorPos = clickedPos.relative(hitResult.getDirection());
			Optional<PortalFrame> frame = PortalFrame.findForIgnition(level, interiorPos, definition.get().framePredicate());

			if (frame.isEmpty()) {
				return InteractionResult.PASS;
			}

			if (level.isClientSide()) {
				return InteractionResult.SUCCESS;
			}

			if (!level.mayInteract(player, clickedPos) || !level.mayInteract(player, interiorPos)) {
				return InteractionResult.FAIL;
			}

			frame.get().fill(level, definition.get().portalBlock().defaultBlockState());
			level.playSound(
					player,
					interiorPos,
					SoundEvents.FLINTANDSTEEL_USE,
					SoundSource.BLOCKS,
					1.0F,
					level.getRandom().nextFloat() * 0.4F + 0.8F
			);
			stack.hurtAndBreak(1, player, hand);

			return InteractionResult.SUCCESS;
		});
	}
}
