import {world, system, Player} from "@minecraft/server";
import {shootProjectile,getAttributes,setAttributes} from '../utils.js';
import { CombatManager } from "../classes/combatManager.js";
import { debug, Check, getCooldownTime, clamp, healthParticle, toColor } from "../mathAndCalculations.js";

world.afterEvents.entityHurt.subscribe(event =>{
	const {hurtEntity, damageSource, damage} = event;
	const {damagingEntity: player} = damageSource;
	if (!player || (hurtEntity.getComponent('minecraft:type_family') && hurtEntity.getComponent('minecraft:type_family').hasTypeFamily('inanimate')) || (player.getComponent('minecraft:type_family') && player.getComponent('minecraft:type_family').hasTypeFamily('inanimate'))) return;
// For when the entity is hurt. Handles iframes.
	if ((player instanceof Player) && damageSource.cause == "entityAttack") {
		const { equippableComp, item, stats } = player.getItemStats();
		const currentTime = Date.now();
		const shieldBlock = Check.shieldBlock(currentTime, player, hurtEntity, stats);
		if (!shieldBlock) hurtEntity.__lastAttack = { damage: stats?.damage, time: Date.now() };
		healthParticle(hurtEntity, damage);
	}

//Handles Custom Enchantments For Items
	const mainHand = player.typeId == 'minecraft:player' ? player.getComponent('equippable').getEquipment('Mainhand') : player.getComponent('inventory') ? player.getComponent('inventory').container.getItem(0) : 0;
	if (!mainHand) return;
	const rng = Math.floor(Math.random()*100);
	const rngEffect = Math.floor(Math.random()*28);
	const comboDmg = mainHand.getDynamicProperty('btr:combo') == 1 ? 4 : mainHand.getDynamicProperty('btr:combo') == 2 ? 6 : mainHand.getDynamicProperty('btr:combo') == 3 ? 8 : 2;
	const penetrationDmg = mainHand.hasTag('minecraft:stone_tier') ? 5 : mainHand.hasTag('minecraft:iron_tier') ? 6 : mainHand.hasTag('minecraft:diamond_tier') ? 7 : mainHand.hasTag('minecraft:netherite_tier') ? 8 : 4;
	const disarmChance = mainHand.getDynamicProperty('btr:disarm') == 1 ? 35 : mainHand.getDynamicProperty('btr:disarm') == 2 ? 45 : mainHand.getDynamicProperty('btr:disarm') == 3 ? 55 : 25;
	const reinforcedDmg = mainHand.hasTag('minecraft:stone_tier') ? 3 : mainHand.hasTag('minecraft:iron_tier') ? 4 : mainHand.hasTag('minecraft:diamond_tier') ? 5 : mainHand.hasTag('minecraft:netherite_tier') ? 6 : 2;
	const jaggedRakeDmg = mainHand.hasTag('minecraft:stone_tier') ? 4 : mainHand.hasTag('minecraft:iron_tier') ? 5 : mainHand.hasTag('minecraft:diamond_tier') ? 6 : mainHand.hasTag('minecraft:netherite_tier') ? 7 : 3;
	const stunChance = mainHand.typeId == 'lst:storm_hammer' ? 100 : mainHand.getDynamicProperty('btr:bash') == 1 ? 35 : mainHand.getDynamicProperty('btr:bash') == 2 ? 45 : mainHand.getDynamicProperty('btr:bash') == 3 ? 55 : 25;


//Handles Nunchaku extra damage based on Combo enchantment
	if (mainHand.hasTag('minecraft:is_nunchaku') && rng <= 25) {
		player.dimension.playSound('random.orb', player.location);
		hurtEntity.applyDamage(comboDmg, { cause: 'entityAttack', damagingEntity: player });
	}
//Handles Club's nausea effect for hurtEntity
	if (mainHand.hasTag('minecraft:is_club')) {
		player.dimension.playSound('big.fall', player.location);
		hurtEntity.addEffect('nausea', 10*20, {amplifier: 1,showParticles: true});
	}
//Education enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:education')) {
		const entities = player.dimension.getEntities({ type: "minecraft:xp_orb", location: player.location, maxDistance: 5, closest: 5 });
		if (entities) {
			player.dimension.playSound('random.ding', player.location);
			entities.forEach(entity => {
				entity.dimension.spawnEntity('minecraft:xp_orb', entity.location);
			});
		}
	}
//Fling enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:fling')) {
		player.dimension.playSound('mob.shulker.bullet.hit', player.location);
		hurtEntity.addEffect('levitation', 20, {amplifier: 6, showParticles: false});
	}
//Vampirism enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:vampirism')) {
		system.runTimeout(() => {
			player.getComponent('health').setCurrentValue(player.getComponent('health').currentValue + 1);
		}, 2);
	}
//Envenomed enchantment
	if ((!hurtEntity.getComponent('minecraft:type_family').hasTypeFamily('undead') || !hurtEntity.typeId == 'minecraft:spider' || !hurtEntity.typeId == 'minecraft:cave_spider') && mainHand.hasTag('minecraft:is_sword') && (mainHand.getDynamicProperty('btr:envenomed') || mainHand.typeId == 'lst:sweet_rapier' || mainHand.typeId == 'lst:withered_sword')) {
		hurtEntity.addEffect('poison', 10*20, {amplifier: 1, showParticles: false});
	}
//Duh
	if (!hurtEntity.typeId == 'minecraft:wither_skeleton' && mainHand.hasTag('minecraft:is_sword') && (mainHand.getDynamicProperty('btr:envenomed') || mainHand.typeId == 'lst:sweet_rapier' || mainHand.typeId == 'lst:withered_sword')) {
		hurtEntity.addEffect('wither', 10*20, {amplifier: 1, showParticles: false});
	}
//Freezing enchantment
	if (mainHand.hasTag('minecraft:is_sword') && (mainHand.getDynamicProperty('btr:freezing') || mainHand.typeId == 'lst:frost_glaive')) {
		hurtEntity.addEffect('slowness', 5*20, {amplifier: 3, showParticles: false});
		hurtEntity.addEffect('mining_fatigue', 5*20, {amplifier: 3, showParticles: false});
	}
//Penetration enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:penetration')) {
		hurtEntity.applyDamage(penetrationDmg, { cause: 'magic', damagingEntity: player });
	}
//Atomic Deconstructor enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:atomicDeconstructor') && rng == 1) {
		hurtEntity.applyDamage(1000, { cause: 'entityAttack', damagingEntity: player });
	}
//Handles Disarm Chance based on Disarm enchantment
	if (mainHand.hasTag('minecraft:is_battleaxe') && rng <= disarmChance) {
		player.dimension.playSound('random.break', player.location);
		hurtEntity.addEffect('weakness', 3*20, {amplifier: 255, showParticles: false});
		hurtEntity.addEffect('mining_fatigue', 3*20, {amplifier: 255, showParticles: false});
	}
//Science enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:science') && rng <= 25) {
		player.dimension.spawnParticle('minecraft:huge_explosion_emitter', player.location);
		player.dimension.playSound('random.explode', player.location);
		player.addTag('btr:science');
		shootProjectile(player, 'btr:science');
		system.runTimeout(()=>{player.removeTag('btr:science')},20);
	}
//Reinforced enchantment
	if ((mainHand.hasTag('minecraft:is_pickaxe') || mainHand.hasTag('minecraft:is_shovel')) && mainHand.getDynamicProperty('btr:reinforced')) {
		hurtEntity.applyDamage(reinforcedDmg, { cause: 'entityAttack', damagingEntity: player });
	}
//Jagged Rake enchantment
	if (mainHand.hasTag('minecraft:is_hoe') && mainHand.getDynamicProperty('btr:jaggedRake')) {
		hurtEntity.applyDamage(jaggedRakeDmg, { cause: 'entityAttack', damagingEntity: player });
	}
//Handles Stun Chance based on Bash enchantment
	if (mainHand.hasTag('minecraft:is_hammer')) {
		player.addTag('btr:knockback');
		shootProjectile(player, 'btr:knockback');
		system.runTimeout(()=>{player.removeTag('btr:knockback')},20);
		player.dimension.playSound('damage.fallbig', player.location);
		hurtEntity.addEffect('nausea', 10*20, {amplifier: 1, showParticles: false});
		if (rng <= stunChance) {
			player.dimension.playSound('random.anvil_land', player.location);
			hurtEntity.addEffect('slowness', 3*20, {amplifier: 6, showParticles: false});
		}
	}
//Purging enchantment
	if (mainHand.hasTag('minecraft:is_sword') && mainHand.getDynamicProperty('btr:purging') && rng <= 25) {
switch (rngEffect) {
	case 1:
		hurtEntity.removeEffect('bad_omen');
		break;
	case 2:
		hurtEntity.removeEffect('blindness');
		break;
	case 3:
		hurtEntity.removeEffect('fatal_poison');
		break;
	case 4:
		hurtEntity.removeEffect('hunger');
		break;
	case 5:
		hurtEntity.removeEffect('instant_damage');
		break;
	case 6:
		hurtEntity.removeEffect('levitation');
		break;
	case 7:
		hurtEntity.removeEffect('mining_fatigue');
		break;
	case 8:
		hurtEntity.removeEffect('nausea');
		break;
	case 9:
		hurtEntity.removeEffect('poison');
		break;
	case 10:
		hurtEntity.removeEffect('slowness');
		break;
	case 11:
		hurtEntity.removeEffect('weakness');
		break;
	case 12:
		hurtEntity.removeEffect('wither');
		break;
	case 13:
		hurtEntity.removeEffect('absorption');
		break;
	case 14:
		hurtEntity.removeEffect('conduit_power');
		break;
	case 15:
		hurtEntity.removeEffect('fire_resistance');
		break;
	case 16:
		hurtEntity.removeEffect('haste');
		break;
	case 17:
		hurtEntity.removeEffect('health_boost');
		break;
	case 18:
		hurtEntity.removeEffect('instant_health');
		break;
	case 19:
		hurtEntity.removeEffect('jump_boost');
		break;
	case 20:
		hurtEntity.removeEffect('night_vision');
		break;
	case 21:
		hurtEntity.removeEffect('regeneration');
		break;
	case 22:
		hurtEntity.removeEffect('resistance');
		break;
	case 23:
		hurtEntity.removeEffect('saturation');
		break;
	case 24:
		hurtEntity.removeEffect('slow_falling');
		break;
	case 25:
		hurtEntity.removeEffect('speed');
		break;
	case 26:
		hurtEntity.removeEffect('strength');
		break;
	case 27:
		hurtEntity.removeEffect('village_hero');
		break;
	case 28:
		hurtEntity.removeEffect('water_breathing');
		break;
	default:
		break
}
	}
	if (mainHand.typeId == 'lst:holy_dagger') {
		if (itemStack.getComponent('cooldown') && itemStack.getComponent('cooldown').getCooldownTicksRemaining(player) != 0) return;
		player.dimension.playSound('random.orb', player.location);
		player.addEffect('regeneration', 20, {amplifier: 2,showParticles: false});
		mainHand.getComponent('cooldown').startCooldown(player);
	}
	if (mainHand.typeId == 'lst:fiery_katana') {
		player.dimension.playSound('mob.player.hurt_on_fire', player.location);
		hurtEntity.setOnFire(2*20, true);
	}
	if (mainHand.typeId == 'lst:shadow_longsword') {
		if (hurtEntity.typeId !== 'minecraft:player') hurtEntity.addEffect('slowness', 10*20, {amplifier: 2, showParticles: false});
		hurtEntity.addEffect('blindness', 10*20, {amplifier: 1, showParticles: false});
	}
	if (event.damageSource.damagingEntity?.typeId === "minecraft:player") {
		let finalDamage = event.damage;
		let damagingEntityAttributes = {
			attackDamage: 1,
			projectileDamage: 1,
			criticalChance: 0,
			criticalDamage: 1.5,
			blockChance: 0,
			parryChance: 0,
			damageReduction: 1,
			evasionChance: 0,
			movementSpeed: 1
		};
		getAttributes(event.damageSource.damagingEntity, damagingEntityAttributes);
		if (event.damageSource.cause === "entityAttack") {
			finalDamage = finalDamage * damagingEntityAttributes.attackDamage;
		}
		if (event.damageSource.cause === "projectile") {
			finalDamage = finalDamage * damagingEntityAttributes.projectileDamage;
		}
		if (Math.random() < damagingEntityAttributes.criticalChance && damagingEntityAttributes.criticalDamage > 1) {
			finalDamage = finalDamage * damagingEntityAttributes.criticalDamage;
		}
		if (event.hurtEntity.typeId === "minecraft:player") {
			let hurtEntityAttributes = {
				attackDamage: 1,
				projectileDamage: 1,
				criticalChance: 0,
				criticalDamage: 1.5,
				blockChance: 0,
				parryChance: 0,
				damageReduction: 1,
				evasionChance: 0,
				movementSpeed: 1
			};
			getAttributes(event.hurtEntity, hurtEntityAttributes);
			if (Math.random() < hurtEntityAttributes.evasionChance) {
				finalDamage = 0;
			} else if (Math.random() < hurtEntityAttributes.parryChance) {
				finalDamage = 0;
			} else if (Math.random() < hurtEntityAttributes.blockChance) {
				finalDamage = finalDamage / 2;
			}
			finalDamage = finalDamage * hurtEntityAttributes.damageReduction;
		}
		if (finalDamage === event.damage) {
			return;
		} else {
			const health = event.hurtEntity.getComponent('health');
			const finalHealth = health.currentValue + event.damage - finalDamage;
			health.setCurrentValue(finalHealth);
			return;
		}
	}
	if (event.damageSource.damagingEntity !== void 0 && event.hurtEntity.typeId === "minecraft:player") {
		let finalDamage = event.damage;
		let hurtEntityAttributes = {
			attackDamage: 1,
			projectileDamage: 1,
			criticalChance: 0,
			criticalDamage: 1.5,
			blockChance: 0,
			parryChance: 0,
			damageReduction: 1,
			evasionChance: 0,
			movementSpeed: 1
		};
		getAttributes(event.hurtEntity, hurtEntityAttributes);
		if (Math.random() < hurtEntityAttributes.evasionChance) {
			finalDamage = 0;
		} else if (Math.random() < hurtEntityAttributes.parryChance) {
			finalDamage = 0;
		} else if (Math.random() < hurtEntityAttributes.blockChance) {
			finalDamage = finalDamage / 2;
		}
		finalDamage = finalDamage * hurtEntityAttributes.damageReduction;
		if (finalDamage === event.damage) {
			return;
		} else {
			const health = event.hurtEntity.getComponent('health');
			const finalHealth = health.currentValue + event.damage - finalDamage;
			health.setCurrentValue(finalHealth);
			return;
		}
	}
	if (event.damageSource.damagingEntity === void 0 && event.hurtEntity.typeId === "minecraft:player") {
		let finalDamage = event.damage;
		let hurtEntityAttributes = {
			attackDamage: 1,
			projectileDamage: 1,
			criticalChance: 0,
			criticalDamage: 1.5,
			blockChance: 0,
			parryChance: 0,
			damageReduction: 1,
			evasionChance: 0,
			movementSpeed: 1
		};
		getAttributes(event.hurtEntity, hurtEntityAttributes);
		finalDamage = finalDamage * hurtEntityAttributes.damageReduction;
		if (finalDamage === event.damage) {
			return;
		} else {
			const health = event.hurtEntity.getComponent('health');
			const finalHealth = health.currentValue + event.damage - finalDamage;
			health.setCurrentValue(finalHealth);
			return;
		}
	}
});
