
const proj4 = require('proj4');
const https = require('https');

proj4.defs("EPSG:25832", "+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs");

const pos = { lat: 51.4332, lng: 7.6616 }; // Marker position
const size = 0.02;
const bbox = `${pos.lat - size},${pos.lng - size},${pos.lat + size},${pos.lng + size},urn:ogc:def:crs:EPSG::4326`;
const url = `https://www.wfs.nrw.de/umwelt/erneuerbare_energien_wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=erneuerbare_energien_wfs:WFS_Windenergie&BBOX=${bbox}&COUNT=10`;

https.get(url, (res) => {
    let data = '';
    res.on('data', (chunk) => data += chunk);
    res.on('end', () => {
        const markerUtm = proj4("EPSG:4326", "EPSG:25832", [pos.lng, pos.lat]);
        console.log("Marker UTM:", markerUtm);

        const blocks = data.split(/<wfs:member[^>]*>/);
        console.log("Found turbines:", blocks.length - 1);

        blocks.slice(1).forEach((block, idx) => {
            const posMatch = block.match(/<gml:pos[^>]*>(.*?)<\/gml:pos>/);
            const ibjahrMatch = block.match(/<erneuerbare_energien_wfs:ibjahr[^>]*>(.*?)<\/erneuerbare_energien_wfs:ibjahr>/);
            const statusMatch = block.match(/<erneuerbare_energien_wfs:status[^>]*>(.*?)<\/erneuerbare_energien_wfs:status>/);

            if (posMatch) {
                const coords = posMatch[1].trim().split(/\s+/).map(Number);
                const d = Math.sqrt(Math.pow(coords[0] - markerUtm[0], 2) + Math.pow(coords[1] - markerUtm[1], 2));
                const jahr = ibjahrMatch ? ibjahrMatch[1] : "???";
                const status = statusMatch ? statusMatch[1] : "???";
                console.log(`Turbine ${idx + 1}: Coords=[${coords}], Dist=${d.toFixed(1)}m, Jahr=${jahr}, Status=${status}`);
            }
        });
    });
});
