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

const TAG_ARMOR_EFFECT = 'oct_plev_armor_effect_mining'

// Armor effect on mining armor
function main() {
	
	for (let player of world.getAllPlayers()) {
		const armorEquipped = player.getComponent(EntityEquippableComponent.componentId)

		const hasHelmet = armorEquipped.getEquipment(EquipmentSlot.Head)?.typeId == "oct_plev:mining_helmet";
		const hasChestplate = armorEquipped.getEquipment(EquipmentSlot.Chest)?.typeId == "oct_plev:mining_chestplate";
		const hasLeggings = armorEquipped.getEquipment(EquipmentSlot.Legs)?.typeId == "oct_plev:mining_leggings";
		const hasBoots = armorEquipped.getEquipment(EquipmentSlot.Feet)?.typeId == "oct_plev:mining_boots";

		// const hasFullArmor = hasHelmet && hasChestplate && hasLeggings && hasBoots
		// const hasAnyArmor = hasHelmet || hasChestplate || hasLeggings || hasBoots
		const hasThreeParts = ((hasHelmet && hasChestplate && hasLeggings) || (hasHelmet && hasChestplate && hasBoots) || (hasHelmet && hasLeggings && hasBoots) || (hasChestplate && hasLeggings && hasBoots))

		if(hasThreeParts && !player.hasTag(TAG_ARMOR_EFFECT)) {
			player.addTag(TAG_ARMOR_EFFECT);			
			player.runCommand("/effect @s haste 100000 1 true");
		}
		else if (!hasThreeParts && player.hasTag(TAG_ARMOR_EFFECT)) {
			player.removeTag(TAG_ARMOR_EFFECT);
			player.runCommand("/effect @s haste 0");			
			player.runCommand("/fill ~-4 ~-4 ~-4 ~4 ~4 ~4 air replace light_block [\"block_light_level\"=15]");
		}
	}
}

system.runInterval(main, 5);

// Removing light block on players death
world.afterEvents.entityDie.subscribe((data) => {
    const player = data.deadEntity
	if(player.hasTag(TAG_ARMOR_EFFECT)) {
			player.removeTag(TAG_ARMOR_EFFECT);
			player.runCommand("/fill ~-4 ~-4 ~-4 ~4 ~4 ~4 air replace light_block [\"block_light_level\"=15]");
			// player.runCommand(`setblock ~ ~1 ~ stone`);
		}
	},
	{ "entityTypes": ['minecraft:player']
})