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

const TAG_WATERING_CAN_COOLDOWN = "oct_plev_watering_can_cooldown"
const TAG_WATERING_CAN_COOLDOWN_2 = "oct_plev_watering_can_cooldown_2"

world.afterEvents.itemUse.subscribe(async (event) => {
	const { itemStack, source } = event;
	const player = source;
	const item = itemStack;

	
	if (itemStack.typeId === "oct_plev:watering_can" && !player.hasTag(TAG_WATERING_CAN_COOLDOWN)) {
		player.addTag(TAG_WATERING_CAN_COOLDOWN);
		const actualDamage = item.getComponent("durability").damage;
		if (actualDamage < 1201) {
			// Watering
			player.runCommand('/function oct/plev/watering_can/ray_init');
			player.runCommand('/playsound oct_plev.sound.watering_can_1 @a ~ ~ ~');
	
			// player.runCommand('/say Damage: ' + actualDamage);
			// Damage the tool
			const durability = item.getComponent(ItemComponentTypes.Durability);
	
			if (0 <= actualDamage && actualDamage < 190) {
				durability.damage = 190;
				player.getComponent('equippable').setEquipment('Mainhand', item);	
			}
			else if (190 <= actualDamage && actualDamage < 390) {
				durability.damage = 390;
				player.getComponent('equippable').setEquipment('Mainhand', item);	
			}
			else if (390 <= actualDamage && actualDamage < 590) {
				durability.damage = 590;
				player.getComponent('equippable').setEquipment('Mainhand', item);	
			}
			else if (590 <= actualDamage && actualDamage < 790) {
				durability.damage = 790;
				player.getComponent('equippable').setEquipment('Mainhand', item);	
			}
			else if (790 <= actualDamage && actualDamage < 990) {
				durability.damage = 990;
				player.getComponent('equippable').setEquipment('Mainhand', item);	
			}
			else if (990 <= actualDamage && actualDamage < 1300) {
				durability.damage = 1201;
				player.getComponent('equippable').setEquipment('Mainhand', item);
				player.runCommand('/replaceitem entity @s[hasitem={item=oct_plev:watering_can,location=slot.weapon.mainhand}] slot.weapon.mainhand 0 oct_plev:watering_can_empty');	
			}
		}
		else {
			player.runCommand('/playsound oct_plev.sound.watering_can_empty @a ~ ~ ~');
		}
	}
});


function main() {
	for (let player of world.getAllPlayers()) {
		// Cooldown
		if (player.hasTag(TAG_WATERING_CAN_COOLDOWN) && !player.hasTag(TAG_WATERING_CAN_COOLDOWN_2)) {
			player.addTag(TAG_WATERING_CAN_COOLDOWN_2);
			let WateringCanCooldown = system.runTimeout(() => {
				player.removeTag(TAG_WATERING_CAN_COOLDOWN);
				player.removeTag(TAG_WATERING_CAN_COOLDOWN_2);
				system.clearRun(WateringCanCooldown);
			}, 19);
		}
	}
}
system.runInterval(main, 5);

world.afterEvents.playerSpawn.subscribe((event) => {
	// Remove cooldown tag on join
	event.player.removeTag(TAG_WATERING_CAN_COOLDOWN_2);
});