// priority: 1

// by blueversal

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

StartupEvents.registry('item', (event) => {
	event
		.create('tide_tower_gem')
		.useAnimation('bow')
		.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 == 'tide_tower_gem') {
					item.count--;
				} else if (offHandItem.id == 'tide_tower_gem') {
					offHandItem.count--;
				}
				global.locate_tide_tower(level, entity);
			}
			return itemstack;
		})
		.displayName('Tide Tower Gem')
		.tooltip('Crack it open to reveal the Tide Tower');
});

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

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

	if (!structureHolder) {
		player.tell('Tide Tower 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> You crack the gem open... inside, a message reads: "Tide Tower is at ${coords}"</color></bg>`);
		} else {
			player.tell('Tide Tower found but start was invalid');
		}
	} else {
		player.tell('No Tide Tower found nearby');
	}
};