import { world, system, BlockPermutation } from "@minecraft/server";
import Timer from "../timer/timerClass";

world.afterEvents.itemStartUse.subscribe(eventData => {
    const item = eventData.itemStack;
    const player = eventData.source;

    if (!player.isSneaking) return;


    if (item.typeId == "rustic:tomato" || item.typeId == "rustic:poisonous_tomato") {
        let viewVector = player.getViewDirection();
        const playerRotation = player.getRotation();
        if (playerRotation.x > 30)
            viewVector = {
                x: viewVector.x * 2.1,
                y: viewVector.y * 2.1,
                z: viewVector.z * 2.1
            };
        const spawnLoc = {
            x: player.getHeadLocation().x + viewVector.x,
            y: player.getHeadLocation().y + viewVector.y,
            z: player.getHeadLocation().z + viewVector.z
        };
        const projectile = player.dimension.spawnEntity(item.typeId, spawnLoc);
        projectile.setRotation({ 'x': -playerRotation.x, 'y': -playerRotation.y });
        const viewVectorVelocity = {
            x: viewVector.x * 1.5,
            y: viewVector.y * 1.5,
            z: viewVector.z * 1.5
        };
        projectile.applyImpulse(viewVectorVelocity);

        player.dimension.runCommand(`playsound tomato.throw @a ${player.location.x} ${player.location.y} ${player.location.z} 10`)

        const equipment = player.getComponent('equippable');

        if (player.getGameMode() !== "creative") {
            if (item.amount > 1) {
                item.amount -= 1;
                equipment.setEquipment('Mainhand', item);
            } else if (item.amount === 1) {
                equipment.setEquipment('Mainhand', undefined);
            }
        }
    }
});

world.afterEvents.projectileHitEntity.subscribe(eventData => {
    const projectile = eventData.projectile;

    if (projectile.typeId == "rustic:tomato" || projectile.typeId == "rustic:poisonous_tomato") {
        const entityHit = eventData.getEntityHit().entity
        entityHit.dimension.runCommand(`playsound tomato.splash @a ${entityHit.location.x} ${entityHit.location.y} ${entityHit.location.z} 5`)

        if (entityHit.typeId == "minecraft:player"){

            entityHit.setDynamicProperty("rustic:tomato_splash", true)
        
            let timeHolder = Timer.set(20, "seconds");
    
            let intervalId = system.runInterval(() => {
                let isExpired = Timer.hasExpired(timeHolder);                
            
                if (isExpired) {
                    entityHit.setDynamicProperty("rustic:tomato_splash", false)
                    system.clearRun(intervalId);
                }
            }, 20);
        }
        
        
    }
});
