import {system, world} from "@minecraft/server"

export function getClosestEntity(sourceEntity, identifier) {
    return sourceEntity.dimension.getEntities({
        type: identifier,
        closest: 1,
        location: sourceEntity.location,
        maxDistance: 4
    })[0];
}

export function setScore(entity, scoreboard, value) {
    try {
        entity.runCommand(`scoreboard objectives add ${scoreboard} dummy`);
        entity.runCommand(`scoreboard players set @s ${scoreboard} ${value}`);
    } catch (e) {
        console.warn(e);
    }
}

system.runInterval(() => {
    const overworld = world.getDimension('overworld');
    const raftEntities = overworld.getEntities({
        families: ["raft"]
    });

    for (const raft of raftEntities) {
        const player = getClosestEntity(raft, "minecraft:player");
        if (player !== undefined && !player.hasTag("title") && !player.hasTag("looking_at_pan")) {
            const raftLevel = parseInt(raft.typeId.slice(-1)) + 1;
            const raftHealth = Math.round(raft.getComponent('health').currentValue / 2);

            setScore(raft, "cubc_ra_su:raft_health", raftHealth);

            if (raftHealth < 10) {
                player.runCommand(`execute unless entity @s[hasitem={item=cubc_ra_su:totem,location=slot.weapon.mainhand}] unless entity @e[r=2, type=cubc_ra_su:ballista_seat] run title @s actionbar Raft Level: §a${raftLevel}\n§fHealth: §e${raftHealth}\n§fRepair raft with §eWooden Panels`);
            } else {
                player.runCommand(`execute unless entity @s[hasitem={item=cubc_ra_su:totem,location=slot.weapon.mainhand}] unless entity @e[r=2, type=cubc_ra_su:ballista_seat] run title @s actionbar Raft Level: §a${raftLevel}\n§fHealth: §e${raftHealth}`);
            }

        }
    }
}, 1);
