import { Player, system } from "@minecraft/server";
import { Vector3 } from "../vector/vector3";

/**
 * 
 * @param {Player} player 
 * @param {Vector3} position 
 * @param {number} distance 
 * @param {number} time
 * @param {number} startRot
 */
export function cameraOrbitPosition(player, position, distance, time, startRot, rotateDegrees) {
    time = time * 20
    const playerId = player.id
    let startTick = system.currentTick
    let firstCamera = true
    let waitForCamera = false
    
    const runInt = system.runInterval(() => {
        // Skip if player is no longer valid
        if (!player.isValid()) {
            system.clearRun(runInt)
            return
        }
        
        // calculate rotation based on time, should rotate rotateDegrees in time starting at startRot
        const rotation = (system.currentTick - startTick) / time * rotateDegrees + startRot

        // ease first position
        if (firstCamera) {
            // Use the player's name instead of @p to target the specific player
            player.runCommand(`execute as "${player.name}" positioned ${position.x} ${position.y} ${position.z} rotated as @s rotated ${rotation} 30 positioned ^^1^-${distance} run camera @s set minecraft:free ease 2 in_out_cubic pos ~~~ facing ${position.x} ${position.y} ${position.z}`)
            firstCamera = false
            waitForCamera = true
            system.runTimeout(() => {
                waitForCamera = false
                startTick = system.currentTick + 1
            }, 35)
            return
        }

        if (waitForCamera) return

        // orbit around position - use player name to target the specific player
        player.runCommand(`execute as "${player.name}" positioned ${position.x} ${position.y} ${position.z} rotated as @s rotated ${rotation} 30 positioned ^^1^-${distance} run camera @s set minecraft:free ease 0.1 linear pos ~~~ facing ${position.x} ${position.y} ${position.z}`)
    })
    
    system.runTimeout(() => {
        system.clearRun(runInt)
        if (player.isValid()) {
            player.runCommand(`camera @s set minecraft:free ease 1.5 in_out_cubic pos ~ ~1.62 ~ rot ~ ~`)
            system.runTimeout(() => {
                if (player.isValid()) {
                    player.runCommand(`camera @s clear`)
                }
            }, 30)
        }
    }, time + 35)
}