import { world, system, EquipmentSlot, ItemStack, Player } from "@minecraft/server";
import * as defaultWorldArrays from "../arrays/default_world_arrays.js"
import * as UIComponents from "./ui_components.js"
import * as itemArrays from "../arrays/item_arrays.js"
import * as itemUtilities from "../utilities/item_utilities.js"

world.afterEvents.itemStartUse.subscribe(({itemStack:item,source:player,useDuration}) => {
	if (item.typeId!="megaverse:draconic_horn") return;
	const results = player.getEntitiesFromViewDirection({maxDistance:128,ignoreBlockCollision:false,includePassableBlocks:false,families: ["dragon"]});
	const dragon = results?.[0]?.entity;
	if (!dragon) return player.onScreenDisplay.setActionBar({rawtext:[{translate:"action.interact.megaverse:dragon_none"}]});
	const isBaby = dragon.getComponent("minecraft:is_baby");
	if (isBaby) return;
	const tameable = dragon.getComponent("minecraft:tameable");
	if (!tameable) return player.onScreenDisplay.setActionBar({rawtext:[{translate:dragon.localizationKey},{text:" "},{translate:"action.interact.megaverse:dragon_wild"}]});
	if (!tameable.isTamed) return player.onScreenDisplay.setActionBar({rawtext:[{translate:dragon.localizationKey},{text:" "},{translate:"action.interact.megaverse:dragon_no_owner"}]});
	if (dragon.typeId=="megaverse:fire_dragon") {
		const followWanderState = dragon.getProperty("megaverse:follow_wander_state");
		if (player.id==tameable.tamedToPlayerId) {
			if (followWanderState=="wander") {
				dragon.triggerEvent("minecraft:dragon_start_follow_owner");
				return player.onScreenDisplay.setActionBar({rawtext:[{text:`${dragon.nameTag}`},{text:" "},{translate:"action.interact.megaverse:dragon_following"}]});
			}
			else {
				dragon.triggerEvent("minecraft:dragon_stop_follow_owner");
				return player.onScreenDisplay.setActionBar({rawtext:[{text:`${dragon.nameTag}`},{text:" "},{translate:"action.interact.megaverse:dragon_wandering"}]});
			}
		}
		else return player.onScreenDisplay.setActionBar({rawtext:[{text:`${dragon.nameTag}`},{text:" "},{translate:"action.interact.megaverse:dragon_not_owned"}]});
	}
	else return player.onScreenDisplay.setActionBar({rawtext:[{text:`${dragon.nameTag}`},{text:" "},{translate:"action.interact.megaverse:dragon_does_not_listen"}]});
});

system.beforeEvents.startup.subscribe(({itemComponentRegistry}) => {
	itemComponentRegistry.registerCustomComponent("megaverse:consume_item_bottle", ConsumeItemBottle);
	itemComponentRegistry.registerCustomComponent("megaverse:consume_cooked_meat", ConsumeCookedMeat);
	itemComponentRegistry.registerCustomComponent("megaverse:consume_raw_meat", ConsumeRawMeat);
	itemComponentRegistry.registerCustomComponent("megaverse:item_tool_durability", ItemToolDurability);
	itemComponentRegistry.registerCustomComponent("megaverse:item_weapon_ability", ItemWeaponAbility);
	itemComponentRegistry.registerCustomComponent("megaverse:item_weapon_durability", ItemWeaponDurability);
	itemComponentRegistry.registerCustomComponent("megaverse:otherworld_mirror", OtherworldMirror);
	itemComponentRegistry.registerCustomComponent("megaverse:otherworld_sword", OtherworldSword);
	itemComponentRegistry.registerCustomComponent("megaverse:use_alchemy_wand", UseAlchemyWand);
	itemComponentRegistry.registerCustomComponent("megaverse:use_wind_instrument", UseWindInstrument);
});
const ConsumeItemBottle = {
	onConsume({itemStack,source}) {
		itemUtilities.itemBottleConsume(itemStack,source);
	}
};
const ConsumeCookedMeat = {
	onConsume({itemStack,source},{params}) {
		itemUtilities.cookedMeatConsume(itemStack,source,params);
	}
};
const ConsumeRawMeat = {
	onConsume({itemStack,source},{params}) {
		itemUtilities.rawMeatConsume(itemStack,source,params);
	}
};
const ItemToolDurability = {
	onBeforeDurabilityDamage({attackingEntity:player,itemStack}) {
		system.run(()=>{
			itemUtilities.itemToolDamage(itemStack,player);
		});
	},
	onMineBlock({itemStack,source:player}) {
		itemUtilities.itemToolDamage(itemStack,player);
	}
};
const ItemWeaponAbility = {
	onHitEntity({attackingEntity,hadEffect,hitEntity},{params}) {
		itemUtilities.itemWeaponAbilityHitEntity(attackingEntity,hadEffect,hitEntity,params);
	}
};
const ItemWeaponDurability = {
	onMineBlock({itemStack,source:player}) {
		itemUtilities.itemToolDamage(itemStack,player);
	}
};
const OtherworldMirror = {
	onUse({source}) {
		const mainhand = source.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
		if (!mainhand.hasItem()) return;
		if (source.isSneaking==false) {
			source.playSound('vault.activate',{location:source.location});
			UIComponents.OtherworldMirrorUI(source);
		}
		if (source.isSneaking) {
			source.dimension.spawnParticle("megaverse:otherworld_mirror_summoning", source.location);
			source.playSound('vault.activate',{location:source.location});
			mainhand.setItem(new ItemStack("megaverse:otherworld_sword"));
		}
	},
	onHitEntity({attackingEntity,hadEffect,hitEntity}) {
		const mainhand = attackingEntity.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
		if (!mainhand.hasItem()) return;
		if (attackingEntity.isSprinting) hitEntity.addEffect("fatal_poison",100,{amplifier:2,showParticles:false});
		else hitEntity.addEffect("wither",100,{amplifier:2,showParticles:false});
		hitEntity.applyImpulse({
			x:attackingEntity.getViewDirection().x+attackingEntity.getVelocity().x,
			y:attackingEntity.getViewDirection().y+(-attackingEntity.getVelocity().y/2),
			z:attackingEntity.getViewDirection().z+attackingEntity.getVelocity().z
		});
		attackingEntity.startItemCooldown("otherworld_sword",20);
		attackingEntity.playSound('vault.activate',{location:attackingEntity.location});
		mainhand.setItem(new ItemStack("megaverse:otherworld_sword"));
	},
	onUseOn({source}) {
		const mainhand = source.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);
		if (!mainhand.hasItem()) return;
		if (source.isSneaking) {
			if (source.getItemCooldown("otherworld_mirror")==0) {
				source.dimension.spawnParticle("megaverse:otherworld_mirror_restoration", source.location);
				source.playSound('vault.activate',{location:source.location});
				mainhand.setItem(new ItemStack("megaverse:otherworld_sword"));
			}
		}
	}
};
const OtherworldSword = {
	onHitEntity({attackingEntity,hadEffect,hitEntity}) {
		const mainhand = attackingEntity.getComponent("minecraft:equippable").getEquipmentSlot("Mainhand");
		if (!mainhand.hasItem()) return;
		hitEntity.applyImpulse({
			x:-hitEntity.getVelocity().x,
			y:-hitEntity.getVelocity().y,
			z:-hitEntity.getVelocity().z
		});
	},
	onUse({source}) {
		const mainhand = source.getComponent("minecraft:equippable").getEquipmentSlot("Mainhand");
		if (!mainhand.hasItem()) return;
		if (source.isSneaking) {
			source.dimension.spawnParticle("megaverse:otherworld_mirror_restoration", source.location);
			source.playSound('vault.deactivate',{location:source.location});
			mainhand.setItem(new ItemStack("megaverse:otherworld_mirror"));
		}
	}
};
const UseAlchemyWand = {
	onCompleteUse({itemStack,source}) {
		itemUtilities.itemToolDamage(itemStack,source);
		itemUtilities.alchemyWandUse(itemStack,source);
	}
};
const UseWindInstrument = {
	onUse({itemStack,source}) {
		itemUtilities.windInstrumentUse(itemStack,source);
	}
};