import { system, ItemStack, world } from '@minecraft/server';
import { riskless, wObjectives } from 'vars.js';
import { lightningParticle, countDisAlpha, countDis } from 'funs.js';
import { itemLores } from 'text.js';

system.afterEvents.scriptEventReceive.subscribe((msg) => {
	let p = msg.sourceEntity,
	    t = world.getTimeOfDay(),
	    v = p.getVelocity(),
	    dms = p.dimension,
	    cds = wObjectives[1];
	let pl = p.location;
	switch (msg.id) {
	case 'zy:projectile':
		switch (p.typeId) {
		case 'zy:fallen_star':
			if (!v.x && !v.y && !v.z && (p.hasTag('shot') || (p.hasTag('nature') && !p.hasTag('pickupable')))) {
				for (let i = 0; i < 6; i++)
					dms.spawnParticle('zy:star', pl);
				p.runCommandAsync('kill');
			} else if (p.hasTag('nature')) {
				if (t > 23000 || t < 12650) {
					for (let i = 0; i < 6; i++)
						dms.spawnParticle('zy:star', pl);
					p.runCommandAsync('kill');
				} else if (!v.x && !v.y && !v.z) {
					if (!p.hasTag('on_ground')) {
						for (let i = 0; i < 6; i++)
							dms.spawnParticle('zy:star', pl);
						p.addTag('on_ground');
					}
				} else if (p.hasTag('on_ground'))
					p.removeTag('on_ground');
			}
			if (!v.x && !v.y && !v.z && p.hasTag('pickupable'))
				p.runCommandAsync('function star_pickup');
			if (v.y > -2 && p.hasTag('fall'))
				p.applyImpulse({ x: 0, y: -0.2, z: 0 });
			break;
		case 'zy:health_sugarcube':
			if (!v.x && !v.y && !v.z) {
				let m = p.getComponent('minecraft:projectile').owner?.getGameMode();
				if (m != 'creative')
					dms.spawnItem(new ItemStack('zy:health_sugarcube'), pl);
				p.runCommandAsync('kill');
			}
			break;
		case 'zy:star_cluster':
			if (Math.abs(v.y) < 0.05) {
				let owner = p.getComponent('minecraft:projectile').owner;
				for (let i = 0; i < 16; i++) {
					let e = dms.spawnEntity('zy:fallen_star', { x: pl.x, y: pl.y + 20, z: pl.z });
					e.applyImpulse({ x: Math.random() * 0.8 - 0.4, y: Math.random() * 2 - 4, z: Math.random() * 0.8 - 0.4 });
					e.addTag('fall');
					e.getComponent('minecraft:projectile').owner = owner;
					if (i < 6)
						dms.spawnParticle('zy:star', pl);
				}
				p.runCommandAsync('kill');
			}
			break;
		case 'zy:dawn_order':
			if (!v.x && !v.y && !v.z)
				p.runCommandAsync('kill');
			break;
		}
		break;
	case 'zy:bluebell':
		for (let e of dms.getEntities({ location: pl, maxDistance: 4 }))
			if (!riskless.includes(e.typeId) && e.typeId != 'minecraft:player' && e.getComponent('minecraft:projectile')?.owner != p) {
				let d = countDis(p, e),
				    el = e.location;
				let vx = (el.x - pl.x) * 2 / d,
				    vy = (el.y - pl.y - 1) * 2 / d,
				    vz = (el.z - pl.z) * 2 / d;
				e.clearVelocity();
				e.applyImpulse({ x: vx, y: vy, z: vz });
			}
		break;
	case 'zy:stargive':
		let star = new ItemStack('zy:fallen_star');
		star.setLore(itemLores.fallen_star);
		dms.spawnItem(star, pl);
		p.runCommandAsync(`playsound random.pop @a ~~~ 0.25 ${Math.random() * 1.6 + 0.6}`);
		break;
	/*case 'zy:fly':
		let tgt = dms.getEntities({ closest: 1, type: 'minecraft:player' })[0];
		p.clearVelocity();
		p.applyImpulse(throwSpeed(p, tgt));
		break;*/
	case 'zy:respawned':
		p.applyDamage(19, { cause: 'suicide' });
		p.runCommandAsync('effect @s resistance 3 4 true');
		p.removeTag('respawned');
		break;
	case 'zy:boss':
		let h = p.getComponent('minecraft:health').currentValue,
		    ply = dms.getPlayers({ location: pl, maxDistance: 64, excludeGameModes: ['creative', 'spectator'] }),
		    np = dms.getPlayers({ closest: 1, location: pl, maxDistance: 64, excludeGameModes: ['creative', 'spectator'] }),
	      cd = cds?.getScore(p);
			  //brz = wObjectives[0]?.getScore(p);
		switch (p.typeId) {
		case 'zy:king_slime':
			let scale = h * 7 / 4304 + 0.125,
		      tgt = dms.getPlayers({ closest: 1, location: pl, minDistance: 10, maxDistance: 64, excludeGameModes: ['creative', 'spectator'] });
			if (/*Math.random() < 0.05 && */!p.hasTag('slimeking_tp'))
				p.runCommandAsync(`execute positioned ~~${scale * 2.08}~ run damage @e[r=${scale * 3.6},family=!monster] 10 entity_attack entity @s`);
			if (Math.random() < 0.008)
				p.addEffect('jump_boost', 20, { amplifier: 3, showParticles: false });
			if (Math.random() < 0.005 && !p.hasTag('slimeking_tp') && tgt.length) {
				let l = tgt[0].location;
				//wObjectives[0]?.setScore(p, 80)
				p.addEffect('resistance', 80, { amplifier: 4, showParticles: false });
				p.addTag('kingslime_tp');
				system.runTimeout(() => {
					p.runCommandAsync(`tp ${l.x} ${l.y} ${l.z}`);
					p.removeTag('kingslime_tp');
				}, 40);
			}
			if (p.hasTag('kingslime_tp'))
				p.clearVelocity();
			break;
		case 'zy:dawn_lord':
			if (h > 360 && !cd && np[0] && !p.hasTag('freezed')) {
				let ordered = (dms.getPlayers({ location: pl, maxDistance: 64, excludeGameModes: ['creative', 'spectator'], tags: ['dawn_ordered'] }).length ? true : false);
				if (Math.random() < 0.02 && !ordered) {
					let sl = { ...pl },
					    tl = { ...np[0].location };
					//let vb = countDisAlpha(sl, tl);
					sl.y += 2.5;
					tl.y += 1.5;
					//world.sendMessage(`${tl.x} ${tl.y} ${tl.z}`);
					let pjt = dms.spawnEntity('zy:dawn_order', sl).getComponent('minecraft:projectile');
					pjt.shoot({ x: (tl.x - sl.x) / 4, y: (tl.y - sl.y) / 4, z: (tl.z - sl.z) / 4 }, { uncertainty: 2 });
					pjt.owner = p;
					cds?.setScore(p, 5);
				} else if (Math.random() < 0.03 * (ordered ? 2 : 1)) {
					for (let oply of ply) {
						let plyl = { ...oply.location };
						plyl.x = Math.floor(plyl.x) + 0.5;
						plyl.y = Math.floor(plyl.y);
						plyl.z = Math.floor(plyl.z) + 0.5;
						dms.spawnEntity('zy:dawn_bright', plyl);
						cds?.setScore(p, 30);
					}
				}
			}
			break;
		}
		if (!dms.getPlayers({ location: pl, maxDistance: 64, excludeGameModes: ['spectator'] }).length) {
			if (!p.hasTag('boss_remove')) {
				p.addTag('boss_remove');
				system.runTimeout(() => {
					if (p.hasTag('boss_remove'))
						p.remove();
				}, 100);
			}
		} else
			p.removeTag('boss_remove');
		break;
	case 'zy:remove':
		if (p.typeId != 'minecraft:player')
			p.remove();
		break;
	case 'zy:lightning':
		let para = msg.message.split(' ');
		//world.sendMessage(msg.message);
		lightningParticle(dms, { x: Number(para[0]), y: Number(para[1]), z: Number(para[2]) }, { x: Number(para[3]), y: Number(para[4]), z: Number(para[5])}, Number(para[6]), Number(para[7]));
		break;
	case 'zy:freeze':
		p.runCommandAsync('tp ~~~~~');
	}
});