// priority: 1

// by blueversal

Platform.mods.kubejs.name = 'Beyond Ascension';

StartupEvents.registry('item', (event) => {
	event
		.create('minecell_portal_locator')
		.useAnimation('eat')
		.rarity('rare')
		.maxStackSize(1)
		.use((level, player, hand) => true)
		.useDuration((itemstack) => 1)
		.finishUsing((itemstack, level, entity) => {
			if (entity.player) {
				let item = entity.getHeldItem('main_hand');
				let offHandItem = entity.getHeldItem('off_hand');

				if (item.id == 'kubejs:minecell_portal_locator') {
					item.count--;
				} else if (offHandItem.id == 'kubejs:minecell_portal_locator') {
					offHandItem.count--;
				}
				global.locate_minecell_portal(level, entity);
			}
			return itemstack;
		})
		.displayName('Minecell Portal Locator')
		.tooltip('Reveals the coordinates of the nearest Minecell Portal');
});

let ServerLevel = Java.loadClass('net.minecraft.server.level.ServerLevel');
let BlockPos = Java.loadClass('net.minecraft.core.BlockPos');
let ChunkPos = Java.loadClass('net.minecraft.world.level.ChunkPos');
let SectionPos = Java.loadClass('net.minecraft.core.SectionPos');
let Registries = Java.loadClass('net.minecraft.core.registries.Registries');
let HolderSet = Java.loadClass('net.minecraft.core.HolderSet');

global.locate_minecell_portal = (level, player) => {
	if (!(level instanceof ServerLevel)) return;

	let registryAccess = level.registryAccess();
	let structureRegistry = registryAccess.registryOrThrow(Registries.STRUCTURE);
	let structureKey = structureRegistry
		.getResourceKey(structureRegistry.get('minecells:overworld_portal'))
		.get();
	let structureHolder = structureRegistry.getHolderOrThrow(structureKey);

	if (!structureHolder) {
		player.tell('Minecell Portal not found');
		return;
	}

	let structure = structureHolder.get();
	let holderSet = HolderSet.direct([structureHolder]);
	let origin = new BlockPos(player.getBlockX(), player.getBlockY(), player.getBlockZ());

	let generator = level.getChunkSource().getGenerator();
	let result = generator.findNearestMapStructure(level, holderSet, origin, 10000, false);

	if (result != null) {
		let pos = result.getFirst();
		let chunkPos = new ChunkPos(pos);
		let sectionPos = SectionPos.of(chunkPos, level.getMinSection());
		let chunk = level.getChunk(chunkPos.x, chunkPos.z);

		let start = level.structureManager().getStartForStructure(sectionPos, structure, chunk);
		if (start && start.isValid()) {
			let piece = start.getPieces()[0];
			let { x, y, z } = piece.locatorPosition;

			let coords = `X:${x} Y:${y} Z:${z}`;
			level.server.runCommandSilent(`/eta send ${player.username} 250 <bg color=#60000000><color value=#FFFF00>Nearest Minecell Portal is at ${coords}</color></bg>`);
		} else {
			player.tell('Minecell Portal found but start was invalid');
		}
	} else {
		player.tell('No Minecell Portal found nearby');
	}
};