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

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


export function ballista() {
    const overworld = world.getDimension('overworld');
    const ballistaEntities = overworld.getEntities({
        families: ["ballista"],
        tags: ["cubc_ra_su_has_rider"]
    });

    for (const ballistaEntity of ballistaEntities) {
        ballistaEntity.runCommand("tag @e[type=player] remove cubc_ra_su_ballista_rider");
        ballistaEntity.runCommand("tag @p add cubc_ra_su_ballista_rider");

        const {x, y, z} = ballistaEntity.location;
        const riders = overworld.getEntities({
            families: ["player"],
            tags: ["cubc_ra_su_ballista_rider"]
        });

        if (riders.length > 0) {
            const rider = riders[0];
            const angle = rider.getRotation();

            rider.runCommand(`scoreboard objectives add cubc_ra_su_rotation dummy`);
            rider.runCommand(`scoreboard objectives add cubc_ra_su_current_rot dummy`);
            rider.runCommand(`scoreboard players add @s cubc_ra_su_current_rot 0`);

            ballistaEntity.setRotation({x: 0, y: angle.y});
            ballistaEntity.setProperty("cubc_ra_su:rotation", angle.y);
            fix_angle(rider, parseInt(angle.y));
        }
    }
}

export function fix_angle(rider, angle) {
    rider.runCommand(`scoreboard players set @s cubc_ra_su_rotation ${angle}`);

    const current_angle = getScore(rider, 'cubc_ra_su_current_rot') % 360;
    let diff = angle - current_angle;
    diff = ((diff + 180) % 360) - 180;
    let new_angle = current_angle + Math.floor(diff / 5);

    if (Math.floor(diff / 5) === 0) {
        new_angle += diff;
    }

    rider.runCommand(`scoreboard players set @s cubc_ra_su_current_rot ${new_angle}`)
    // rider.runCommand(`title @s actionbar Rotation: ${rotation} | Cur: ${current_rot} | diff: ${diff}`);
    let rotate_name = `cubc_ra_su:rotate_${new_angle}`.replace('-', '_');
    rider.runCommand(`event entity @e[c=1, type=cubc_ra_su:ballista_seat] ${rotate_name}`);
}