import { world, system, Dimension } from "@minecraft/server";

const overworld = world.getDimension("overworld");
const nether = world.getDimension("nether");
const the_end = world.getDimension("the_end");

function Vector3(x, y, z) {
	if (typeof x !== 'number' || typeof y !== 'number' || typeof z !== 'number') {
		throw new Error('Invalid arguments: x, y, z must be numbers.');
	}

	this.x = x;
	this.y = y;
	this.z = z;
}

function isVector3(obj) {
	return (
		typeof obj === 'object' &&
		obj !== null &&
		obj.hasOwnProperty('x') &&
		obj.hasOwnProperty('y') &&
		obj.hasOwnProperty('z') &&
		typeof obj.x === 'number' &&
		typeof obj.y === 'number' &&
		typeof obj.z === 'number'
	);
}



export function detectLoadedChunk(chunkLoc, chunkDim=overworld, tickInterval=5, tickTimeout=100) {

	if (!isVector3(chunkLoc) || !(chunkDim instanceof Dimension)) {
		return Promise.resolve({ status: 'invalid', data: `Invalid arguments.` });
	}

	if (chunkDim.getBlock(chunkLoc)) {
		return Promise.resolve({ status: 'resolved', data: `Chunk already loaded.` });
	}

	let tickCount = 0;

    return new Promise((resolve) => {

		let chunkIntervalTimer = system.runInterval(() => {
			tickCount += tickInterval;

			if (chunkDim.getBlock(chunkLoc)) {
				system.clearRun(chunkIntervalTimer);
				resolve({ status: 'resolved', data: `Chunk loaded after ${tickCount} tick(s).` });
			}

			if (tickCount >= tickTimeout) {
				system.clearRun(chunkIntervalTimer);
				resolve({ status: 'rejected', data: `Chunk detection timed out after ${tickCount} tick(s).` });
			}
		}, tickInterval);
    });

}