import { Centrifuge } from 'npm:centrifuge'

async function find_vehicle_by_id(client, vehicleId) {
    let response = await client.rpc('script.eval', {
        code: `
            function find_vehicle_by_id(vehicle_id)
                local found = sim.map.find_all({
                    groups = { "vehicle" },
                })
                for idx = 1, #found do
                    if sim.object.get_robot_id(found[idx].entity) == vehicle_id then
                        return found[idx].entity
                    end
                end
                return nil
            end

            return find_vehicle_by_id(ARGS.id)
        `,
        args: {
            id: vehicleId,
        }
    });

    return response.data;
}

async function main() {
    let client = new Centrifuge('ws://localhost:9120/connection/websocket')
    await client.connect()

    let vehicle = await find_vehicle_by_id(client, 1)
    if (!vehicle) {
        console.log('No vehicle found')
        return
    }

    let sub = client.newSubscription(`object_${vehicle}.position`)
    sub.on('publication', msg => {
        console.log('drone position:', msg.data)
    })
    sub.subscribe()
}

await main()
