import { system, world } from '@minecraft/server';
import { countDis, defRuleSet } from 'funs.js';
import { scoreBoard, objectivesString, wObjectives, overWorld,
         damageRecC, damageRecA } from 'vars.js';
import { itemLores, eventTips, evilTips, dayTips } from 'text.js';
//import 'componentevent.js';
import 'scriptevent.js';

system.runInterval(() => {
	let t = world.getTimeOfDay(),
	    we = wObjectives[0]?.getScore('worldEvent'),
	    de = wObjectives[0]?.getScore('dayEvent'),
	    elv = Math.floor(world.getDay() / 5),
	    plys = world.getPlayers(),
	    owps = overWorld.getPlayers();
	overWorld.runCommandAsync(`difficulty ${Math.min(elv, 3)}`);
	if ((t > 23000 || t < 12650) && we) {
		if (we != -1)
			world.sendMessage(`§2${eventTips[we * 2 - 1]}`);
		if (Math.random() < 0.25) {
			let r = Math.floor(Math.random() * dayTips.length) + 1;
			if (r > 1 && elv < 1)
				r = 1;
			wObjectives[0]?.setScore('dayEvent', r);
			switch (r) {
			case 1:
				if (owps.length) {
					let l = owps[Math.floor(Math.random() * owps.length)].location;
					let slxz = { x: l.x + Math.random() * 40 - 20, z: l.z + Math.random() * 40 - 20 };
					let b = overWorld.getTopmostBlock(slxz);
					let sl = { x: slxz.x, y: (b ? b.location.y : -64) + 1, z: slxz.z };
					overWorld.spawnEntity('zy:golden_chicken', sl);
				}
				break;
			}
			world.sendMessage(`§2${dayTips[r - 1]}`);
		}
		wObjectives[0].setScore('worldEvent', 0);
		if (!(world.getDay() % 5)) {
			switch (elv) {
			case 0:
			}
			let text = evilTips[elv];
			if (text)
				world.sendMessage(`§2${text}`);
		}
	} else if (t > 12650 && t < 23000 && !we) {
		wObjectives[0]?.setScore('dayEvent', 0);
		if (Math.random() < 0.25) {
			let r = Math.floor(Math.random() * eventTips.length / 2) + 1;
			wObjectives[0]?.setScore('worldEvent', r);
			world.sendMessage(`§2${eventTips[r * 2 - 2]}`);
		} else
			wObjectives[0]?.setScore('worldEvent', -1);
	}
	//damageRecA = damageRecA.filter((obj) => (- obj.time <= 20));
	if (Math.random() < 0.5) {
		overWorld.runCommandAsync('execute at @e[type=zy:fallen_star,tag=on_ground] run particle zy:star_light ~~~');
		overWorld.runCommandAsync('execute at @e[type=zy:golden_chicken] run particle zy:golden_light ~~~');
	}
	for (let p of plys) {
		for (let i = 0; i < 36; i++) {
			let cont = p.getComponent('inventory').container;
			let item = cont.getItem(i);
			let text = itemLores[item?.typeId.split(':')[1]];
			if (!item?.getLore().length && text)
				item.setLore(text);
				cont.setItem(i, item);
			/*for (let t of itemLores)
				if (!item?.getLore().length && t.item == item?.typeId) {
					item.setLore(t.text);
					cont.setItem(i, item);
				}*/
		}
		if (!p.hasTag('musicplay_bossdawn') && !p.hasTag('musicplay_bosstr')) {
			if (p.hasTag('bossfight_dawnlord')) {
				p.addTag('musicplay_bossdawn');
				p.playMusic('music.boss.dawn', { loop: true, fade: 3 });
				p.removeTag('musicplay_normal');
			} else if (p.hasTag('bossfight_kingslime')) {
				p.addTag('musicplay_bosstr');
				//p.stopMusic();
				p.playMusic('music.boss.tr', { loop: true, fade: 3 });
				p.removeTag('musicplay_normal');
			} else if (!p.hasTag('musicplay_normal')) {
				p.addTag('musicplay_normal');
				p.playMusic('music.game', { loop: true, fade: 3 });
			}
		}
	}
	for (let p of owps) {
		let l = p.location;
		//let r = Math.random();
		//p.runCommandAsync(`title @s actionbar ${p.dimension.id}`);
		if (t > 12650 && t < 23000 && (owps.length ? (Math.random() < 0.005 / owps.length) : false)) {
			let slxz = { x: l.x + Math.random() * 64 - 32, z: l.z + Math.random() * 64 - 32 };
			let b = overWorld.getTopmostBlock(slxz);
			let sl = { x: slxz.x, y: (b ? b.location.y : -64) + 160, z: slxz.z };
			overWorld.spawnEntity('zy:fallen_star', sl);
			//world.sendMessage('b');
		} 
	}
	switch (de) {
	case 2:
		for (let p of owps) {
				if ((owps.length ? (Math.random() < 0.05 / owps.length) : false)) {
				let slxz = { x: p.location.x + Math.random() * 64 - 32, z: p.location.z + Math.random() * 64 - 32 };
				let b = overWorld.getTopmostBlock(slxz);
				let sl = { x: slxz.x, y: (b ? b.location.y : -64) + 40, z: slxz.z };
				overWorld.spawnEntity('zy:minion_slime', sl).applyImpulse({ x: Math.random() * 1 - 0.5, y: Math.random() * 4 - 6, z: Math.random() * 1 - 0.5 });
			}
		}
		break;
	}
	switch (we) {
	case 1:
		for (let p of owps) {
			if ((owps.length ? (Math.random() < 0.2 / owps.length) : false)) {
				let l = p.location;
				let slxz = { x: l.x + Math.random() * 64 - 32, z: l.z + Math.random() * 64 - 32 };
				let b = overWorld.getTopmostBlock(slxz);
				let sl = { x: slxz.x, y: (b ? b.location.y : -64) + 160, z: slxz.z };
				let e = overWorld.spawnEntity('zy:fallen_star', sl);
				if (Math.random() < 0.975)
					e.addTag('unable_to_pickup');
			}
		}
		break;
	default:
		break;
	}
});

world.afterEvents.entityHurt.subscribe((msg) => {
	let p = msg.hurtEntity,
	    k = msg.damageSource.damagingEntity,
	    s = msg.damageSource.damagingProjectile;
	switch (s?.typeId) {
	case 'zy:fallen_star':
		for (let i = 0; i < 6; i++)
			p.dimension.spawnParticle('zy:star', s.location);
		if (s.hasTag('critical_hit'))
			p.dimension.spawnParticle('minecraft:critical_hit_emitter', s.location);
		break;
	case 'zy:dawn_order':
		wObjectives[2]?.setScore(p, 40);
		p.runCommandAsync('particle zy:dawn_order_notice ~~2.5~');
		p.addTag('dawn_ordered');
		p.addEffect('weakness', 40, { amplifier: 9, showParticles: false });
		p.addEffect('mining_fatigue', 40, { amplifier: 9, showParticles: false });
		break;
	}
	if (p.typeId == 'zy:king_slime')
		p.runCommandAsync('summon zy:minion_slime');
});

world.afterEvents.worldInitialize.subscribe(() => {
	defRuleSet();
	for (let objective of objectivesString) {
		if (!scoreBoard.getObjective(objective)) {
			scoreBoard.addObjective(objective);
			wObjectives.push(scoreBoard.getObjective(objective));
		} else
			wObjectives.push(scoreBoard.getObjective(objective));
	}
});

world.afterEvents.entitySpawn.subscribe((msg) => {
	let p = msg.entity;
	switch (p.typeId) {
	case 'zy:fallen_star': 
		let v = p.getVelocity();
		if (!v.x && !v.y && !v.z) {
			p.applyImpulse({ x: Math.random() * 1 - 0.5, y: Math.random() * 4 - 6, z: Math.random() * 1 - 0.5 });
			p.runCommandAsync('event entity @s zy:nature');
			p.addTag('nature');
			p.addTag('pickupable');
			p.addTag('fall');
		} else {
			p.addTag('shot');
			//let r = Math.random();
			if (Math.random() < 0.04) {
				p.addTag('critical_hit');
				p.runCommandAsync('event entity @s zy:critical_hit');
				//world.sendMessage('ch');
			}
		}
		break;
	case 'zy:king_slime':
		world.sendMessage('§4史莱姆王已苏醒!');
		p.runCommandAsync('playsound sound.warcry.tr @a');
		break;
	}
});

world.afterEvents.entityDie.subscribe((msg) => {
	let p = msg.deadEntity,
	    k = msg.damageSource.damagingEntity;
	if (p.typeId == 'minecraft:player') {
		if (k?.typeId == 'minecraft:player')
			p.addTag('respawned');
		else
			p.runCommandAsync('gamemode spectator');
	} else if (p.typeId == 'zy:minion_slime' && wObjectives[0]?.getScore('dayEvent') == 2 && !p.dimension.getEntities({ type: 'zy:king_slime' }).length) {
		wObjectives[0]?.addScore('slime_progress', 1);
		if (wObjectives[0]?.getScore('slime_progress') >= 75) {
			wObjectives[0]?.setScore('slime_progress', 0);
			let owps = overWorld.getPlayers();
			let l = owps[Math.floor(Math.random() * owps.length)].location;
			let slxz = { x: l.x + (Math.random() * 8 + 8) * (Math.random() < 0.5 ? 1 : -1), z: l.z + (Math.random() * 8 + 8) * (Math.random() < 0.5 ? 1 : -1) };
			let b = overWorld.getTopmostBlock(slxz);
			let sl = { x: slxz.x, y: (b ? b.location.y : -64) + 1, z: slxz.z };
			overWorld.spawnEntity('zy:king_slime', sl);
		}
	} else if (p.typeId == 'zy:king_slime') {
		world.sendMessage('§4史莱姆王已被击败!');
		if (wObjectives[0]?.getScore('dayEvent') == 2) {
			world.sendMessage('§2史莱姆停止从天而降。');
			wObjectives[0]?.setScore('dayEvent', 0);
		}
	}
});

world.afterEvents.playerJoin.subscribe((msg) => {
	let p = `\"${msg.playerName}\"`;
	system.runTimeout(() => {
		overWorld.runCommandAsync(`tag ${p} remove musicplay_bosstr`);
		overWorld.runCommandAsync(`tag ${p} remove musicplay_bossdawn`);
		overWorld.runCommandAsync(`tag ${p} remove musicplay_normal`);
	}, 100);
});
/*world.afterEvents.playerBreakBlock.subscribe((msg) => {
	let tools = ['minecraft:iron_pickaxe', 'minecraft:diamond_pickaxe', 'minecraft:netherite_pickaxe'],
	   ores_1 = ['zy:crazigold_ore', 'zy:deepslate_crazigold_ore'],
	   ores_2 = ['zy:healthsand_ore', 'zy:deepslate_healthsand_ore'],
	   block = msg.brokenBlockPermutation.type.id;
	if(tools.includes(msg.itemStackBeforeBreak.typeId)) {
		if(ores_1.includes(block))
			overWorld.runCommandAsync();
	}
});*/