const { RoonExtension } = require('roon-kit');
const fs = require('fs');

const outputTrackFile = "/tmp/roon_track.txt";

const extension = new RoonExtension({
    description: {
        extension_id: 'roon-track-writer',
        display_name: "Roon Track Writer",
        display_version: "0.1.0",
        publisher: 'teraflops',
        email: 'teraflops@example.com'
    },
    RoonApiTransport: 'required',
    subscribe_zones: true
});


extension.on("subscribe_zones", async (core, response, body) => {
    const changedZones = body.zones_changed ?? [];
    const addedZones = body.zones_added ?? [];

    for (const zone of [...changedZones, ...addedZones]) {
        if (zone.state === 'playing') {
            const artist = zone.now_playing?.one_line?.line2 || '';
            const track = zone.now_playing?.one_line?.line1 || '';
            const line = `${artist} - ${track}`;
            fs.writeFileSync(outputTrackFile, line);
            console.log(`🎵 Track escrito: ${line}`);
        }
    }
});

extension.start_discovery();
extension.set_status("Esperando conexión con Roon...");

(async () => {
    const core = await extension.get_core();
    extension.set_status("Emparejado con el Core de Roon");
})();

