// priority: 1

// by blueversal

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

StartupEvents.registry('item', (event) => {
	event
		.create('fish_branded_town')
		.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:fish_branded_town') {
					item.count--;
				} else if (offHandItem.id == 'kubejs:fish_branded_town') {
					offHandItem.count--;
				}
				global.locate_branded_town(level, entity);
			}
			return itemstack;
		})
		.displayName('Town Fish')
		.tooltip('Reveals the coordinates of the nearest Branded Town');
});

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_branded_town = (level, player) => {
	if (!(level instanceof ServerLevel)) return;

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

	if (!structureHolder) {
		player.tell('Branded Town structure 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} 400 <bg color=#60000000><color value=#55FFFF> The fish rolls its eyes: "I’m from a town at ${coords}. We don’t usually eat each other there."</color></bg>`);
		} else {
			player.tell('Branded Town found but start was invalid');
		}
	} else {
		player.tell('No Branded Town found nearby');
	}
};