import { world } from '@minecraft/server';

export function countDis(a, b) {
	let al = a.location,
	    bl = b.location;
	return Math.sqrt((al.x - bl.x) ** 2 + (al.y - bl.y) ** 2 + (al.z - bl.z) ** 2);
}

export function countDisAlpha(a, b) {
	return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2);
}

//function thrSpdHlpFun(d, dy, vy, g) {
//	return d ? Math.sqrt(vy ** 2 / g + vy * Math.sqrt(vy ** 2 - 2 * g * dy) / g / d) : 0
//}

export function throwSpeed(ep, et) {
	let p = ep.location,
	    t = et.location,
	    g = 0.0593;
	//let dy = t.y - p.y;
	//let dyMax = Math.max(p.y, t.y) + 5 - p.y;
	let vy = Math.sqrt(g * 2 * (Math.max(p.y, t.y) + 5 - p.y));
	//return { x: thrSpdHlpFun(t.x - p.x, dy, vy, g), y: vy, z: thrSpdHlpFun(t.z - p.z, dy, vy, g) };
	//let tGet = Math.sqrt(gDbl * dyMax) + Math.sqrt(gDbl * dyMax - gDbl * (t.y - p.y));
	let tGet = (vy + Math.sqrt(vy ** 2 + 2 * g * (p.y - t.y))) / g;
	return { x: (t.x - p.x) / tGet , y: vy, z: (t.z - p.z) / tGet };
}

export function defRuleSet() {
	let r = world.gameRules;
	r.doImmediateRespawn = true;
	r.playersSleepingPercentage = 0.5;
	r.sendCommandFeedback = false;
	r.showTags = false;
	r.keepInventory = false;
}

export function lightningParticle(d, start, end, t, r) {
	let cer = { ...start };
	for (let i = 0; i < t; i++) {
		//world.sendMessage('a');
		let tar = { ...cer };
		tar.x += (end.x - tar.x) / (t - i) + ((t != i + 1) ? ((Math.random() * 2 - 1) * r) : 0);
		tar.y += (end.y - tar.y) / (t - i) + ((t != i + 1) ? ((Math.random() * 2 - 1) * r) : 0);
		tar.z += (end.z - tar.z) / (t - i) + ((t != i + 1) ? ((Math.random() * 2 - 1) * r) : 0);
		//world.sendMessage(`${cer.x} ${cer.y} ${cer.z}`);
		//world.sendMessage(`${tar.x} ${tar.y} ${tar.z}`);
		//world.sendMessage(`${countDisAlpha(cer, tar)}`);
		let dis = countDisAlpha(cer, tar);
		while (dis > 0.1) {
			//world.sendMessage('b');
			d.spawnParticle('zy:lightning', cer);
			for (let e of d.getEntities({ maxDistance: 1, location: cer }))
				e.applyDamage(1, { cause: 'suicide' });
			cer.x += (tar.x - cer.x) / dis * 0.1;
			cer.y += (tar.y - cer.y) / dis * 0.1;
			cer.z += (tar.z - cer.z) / dis * 0.1;
			dis = countDisAlpha(cer, tar);
		}
	}
}