import { world, system, EasingType, EntityRideableComponent, Entity, Player } from "@minecraft/server";
import { GeneralUtils } from "../utils.js"

/**
 * @param {Entity} helicopterEntity - The entity to use for the tick
 * @param {EntityRideableComponent} rideableComponent - The rideable component to use
 */
export const helicopterEntityTick = (helicopterEntity, rideableComponent) => {
    const rider = rideableComponent.getRiders()[rideableComponent.controllingSeat];
    const player_rider = GeneralUtils.world.getPlayerFromEntity(rider);

    const helicopterSpeed = helicopterEntity.getProperty("af:helicopter.speed") / 5;
    const helicopterTurnSpeed = helicopterEntity.getProperty("af:helicopter.turn-speed") ?? 100;
    if (!helicopterSpeed) return;

    let velocity = helicopterEntity.getVelocity()

    if (player_rider) {
        const input = player_rider.inputInfo.getMovementVector();

        const rot = player_rider.getRotation();
        const pitch = GeneralUtils.math.toRad(rot.x + 90);
        const yaw = GeneralUtils.math.toRad(rot.y);

        const upX = Math.sin(yaw) * Math.cos(pitch);
        const upY = Math.sin(pitch);
        const upZ = -Math.cos(yaw) * Math.cos(pitch);

        if (input.y < 0) {
            velocity.x += upX * input.y / 8;
            velocity.y += upY * input.y / 8;
            velocity.z += upZ * input.y / 8;
        } else {
            velocity.x += upX * input.y / 4;
            velocity.y += upY * input.y / (Math.hypot(upX, upZ) + 1) / 4;
            velocity.z += upZ * input.y / 4;
        }

        velocity.x += Math.sin(yaw - Math.PI / 2) * -input.x / 8;
        velocity.z += -Math.cos(yaw - Math.PI / 2) * -input.x / 8;

        velocity = GeneralUtils.math.clampVector(velocity, helicopterSpeed);

        const rotation = GeneralUtils.world.rotateByClamped(helicopterEntity, rot, helicopterTurnSpeed);

        helicopterEntity.setRotation(rotation);
    } else {
        velocity.y = -0.5;
    }

    velocity.x = velocity.x * 0.9;
    velocity.y = velocity.y * 0.9;
    velocity.z = velocity.z * 0.9;

    helicopterEntity.clearVelocity();
    helicopterEntity.applyImpulse(velocity);
}