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);
    }
}

export function getScore(entity, scoreboard) {
    try {
        const score = world.scoreboard.getObjective(scoreboard).getScore(entity)
        if (score === undefined) {
            return 0;
        } else {
            return score;
        }
    } catch {
    }
    // console.warn(`scoreboard ${scoreboard} not found on ${entity.nameTag}`);
    return 0;
}

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);
            const raftLt = getScore(raft, "lifetime");
            if (raftLt > 10) {
                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[tag=!cubc_ra_su_title] 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[tag=!cubc_ra_su_title] actionbar Raft Level: §a${raftLevel}\n§fHealth: §e${raftHealth}`);
                }
            }
        }
    }
}, 1);
