import { EntityEquippableComponent, EntityHealthComponent, EntityInventoryComponent, EquipmentSlot, ItemLockMode, ItemStack, system, world } from "@minecraft/server";
import { getRandomItem } from "../../functions";

const messages = [
    "trueweapons.amputation.line1",
    "trueweapons.amputation.line2",
    "trueweapons.amputation.line3",
    "trueweapons.amputation.line4",
    "trueweapons.amputation.line5"
]

export default {
    async add(item, player) {
        const tag = item?.getTags()?.find(tag => tag == "amputate");
        const isVanillaSword = item.getTags().find(tag => tag == "minecraft:is_sword");

        if (player.typeId != "minecraft:player" || (!tag && !isVanillaSword)) return;
        if (this.isAmputated(player)) return;

        const playerEquippableComponent = player.getComponent(EntityEquippableComponent.componentId);

        if (!playerEquippableComponent) return;
        const playerInventoryContainer = player.getComponent(EntityInventoryComponent.componentId).container;
        const blockerItemStack = new ItemStack("true:barrier", 1);
        const oldOffhandItem = playerEquippableComponent.getEquipment(EquipmentSlot.Offhand);

        if (oldOffhandItem?.typeId == "minecraft:shield" && player.isSneaking) return;
        if (playerEquippableComponent.getEquipment(EquipmentSlot.Chest)) return;
        if (oldOffhandItem?.typeId == "true:barrier" || !this.canAmputate(player)) return;
        if (Math.random() > (10 / 100)) return

        // Visual Thingy
        player.onScreenDisplay.setActionBar({ translate: getRandomItem(messages) });
        player.camera.fade({ fadeColor: { red: 0.5390625, green: 0.015625, blue: 0.04296875 }, fadeTime: { fadeInTime: 0.2, fadeOutTime: 0.2, holdTime: 0.4 } });
        player.playSound("true.player.dismembered", { location: player.location });
        player.playAnimation("animation.player.amputation");

        if (oldOffhandItem) {
            playerInventoryContainer.addItem(oldOffhandItem);
        }
        blockerItemStack.lockMode = ItemLockMode.slot;
        playerEquippableComponent.setEquipment(EquipmentSlot.Offhand, blockerItemStack);   
    },
    isAmputated(player) {
        const playerEquippableComponent = player.getComponent(EntityEquippableComponent.componentId);
        const offHand = playerEquippableComponent.getEquipment(EquipmentSlot.Offhand);

        return offHand && offHand?.typeId == "true:barrier"
    },
    canAmputate(player) {
        const playerHealthComponent = player.getComponent(EntityHealthComponent.componentId);

        return playerHealthComponent.currentValue > 0 && playerHealthComponent.currentValue < 9;
    }
}