/**
 * LLUAV JavaScript SDK - Enhanced Usage Example
 *
 * Demonstrates:
 *   - Auto-reconnect & heartbeat
 *   - Command queue with timeout
 *   - Periodic task scheduler
 *
 * Prerequisites:
 *   npm install ws
 *
 * Usage:
 *   node basic_usage.js [host] [port] [password]
 */

const { LLUAVClient, LLUAVCommandError } = require('../src/client');

function printJson(title, obj, maxLen = 2000) {
    const s = JSON.stringify(obj, null, 2);
    console.log(`\n--- ${title} ---`);
    console.log(s.length > maxLen ? s.slice(0, maxLen) + '\n... [truncated]' : s);
}

async function main() {
    const host = process.argv[2] || 'localhost';
    const port = parseInt(process.argv[3] || '53001', 10);
    const password = process.argv[4] || null;

    const client = new LLUAVClient(host, port, password, 10000, {
        autoReconnect: true,
        heartbeatInterval: 5000,
        heartbeatCmd: 'state',
    });

    try {
        await client.connect();
        console.log(`Connected to ${client.url}`);

        // Register periodic task: get state every 2 seconds
        client.addPeriodicTask('status_poll', 2, 'state');
        console.log('Registered periodic task: status_poll every 2s');

        // Version
        printJson('Version', await client.getVersion());

        // Machine ID
        printJson('Machine ID', await client.getMachineId());

        // System info
        printJson('System Info', await client.getSysinfo());

        // State
        printJson('Drone State', await client.getState());

        // Preflight check
        try {
            printJson('Preflight Check', await client.preflightCheck());
        } catch (e) {
            console.error('Preflight check error:', e.message);
        }

        // Lidar pose
        try {
            printJson('Lidar Pose', await client.getLidarPose());
        } catch (e) {
            console.error('Lidar pose error:', e.message);
        }

        // Wait for periodic tasks
        console.log('\n--- Waiting 6 seconds for periodic tasks ---');
        await new Promise(r => setTimeout(r, 6000));

        client.removePeriodicTask('status_poll');
        console.log('Removed periodic task: status_poll');

        // Example: takeoff (uncomment to execute)
        // printJson('Takeoff', await client.takeoff());

        console.log('\nDone.');
        await client.disconnect();
    } catch (e) {
        if (e instanceof LLUAVCommandError) {
            console.error(`Command failed: ${e.message} (ret=${e.retCode})`);
            console.error('Response:', JSON.stringify(e.response, null, 2));
        } else {
            console.error('Error:', e.message);
        }
        process.exit(1);
    }
}

main();
