import { hasTag } from "../../functions";

const BACKSTABBING_REGEXP = /stabbing:[0-9]+/;
const DAMAGE_REGEXP = /stabbing:([0-9]+)/;

export default {
    execute(weapon, player, target) {
        const tag = hasTag(weapon, null, BACKSTABBING_REGEXP);

        if (!tag) return;
        if (!tag.match(DAMAGE_REGEXP)[0]) return;
        const stabbingDamage = tag.match(DAMAGE_REGEXP)[1];
        const { y: rotY1 } = target.getRotation();
        const { y: rotY2 } = player.getRotation();

        if (!this.isInBack(rotY1, rotY2, 50)) return;
     
        target.applyDamage(Number(stabbingDamage));
    },
    isInBack(rot1, rot2, threshold) {
        const adjustedYourRotation = ((rot2 + 180) % 360) - 180;
        const adjustedEntityRotation = ((rot1 + 180) % 360) - 180;
        const rotationDifference = Math.abs(adjustedYourRotation - adjustedEntityRotation);
      
        return rotationDifference <= threshold;
    }
}