import fs from 'node:fs';
import { dataUriToBuffer } from 'npm:data-uri-to-buffer';
import { Centrifuge } from 'npm:centrifuge'

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

    let vehicle = (await client.rpc('map.spawn_uav', {
        robot_id: 12,
        position: { x: 4, y: 4 },
    })).data

    let camera_rgb = (await client.rpc('map.spawn_camera', {
        // NOTE: tiff is recommended for performance reasons (png is widely supported, but slow to encode)
        format: 'image/png',
        parent: vehicle,
        fov: Math.PI / 4,
    })).data

    let camera_depth = (await client.rpc('map.spawn_camera', {
        format: 'image/png',
        parent: vehicle,
        fov: Math.PI / 4,
        depth_camera: true,
    })).data

    while (true) {
        let [image_rgb, image_depth] = await Promise.all([
            client.rpc(`object_${camera_rgb}.request_image`),
            client.rpc(`object_${camera_depth}.request_image`),
        ])

        for (let { image, filename } of [
            { image: image_rgb.data, filename: 'image_rgb' },
            { image: image_depth.data, filename: 'image_depth' },
        ]) {
            let parsed = dataUriToBuffer(image.data)

            let extension;
            switch (parsed.type) {
                case 'image/png':
                    extension = 'png';
                    break;
                case 'image/jpeg':
                    extension = 'jpg';
                    break;
                case 'image/webp':
                    extension = 'webp';
                    break;
                case 'image/tiff':
                    extension = 'tiff';
                    break;
                case 'image/bmp':
                    extension = 'bmp';
                    break;
                default:
                    throw new Error(`Unsupported image mime type: ${image.mime}`);
            }

            fs.writeFileSync(`${filename}.${extension}`, new Uint8Array(parsed.buffer));
        }
    }
}

await main()
