"""Appendix D.1: download the Brussels Mobility GeoServer layers as GeoJSON (EPSG:4326)."""
import json, urllib.request, urllib.parse, datetime
WFS = 'https://data-mobility.irisnet.be/geoserver/wfs'
UA = {'User-Agent': 'fsd-atlas/1.0'}

def get(layer):
    q = {'service': 'WFS', 'version': '2.0.0', 'request': 'GetFeature', 'typeNames': layer,
         'outputFormat': 'application/json', 'srsName': 'EPSG:4326'}
    url = WFS + '?' + urllib.parse.urlencode(q)
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=120) as r:
        return url, json.load(r)

log = []
for L in ['bm_network:ville30_detailed', 'bm_network:brr_segments_speed', 'bm_network:Zones_30_polygon']:
    url, d = get(L)
    json.dump(d, open(L.split(':')[1] + '.geojson', 'w'))
    log.append((L, url, len(d['features'])))
    print(L, len(d['features']))
json.dump({'fetched': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'queries': log},
          open('bxl_fetchlog.json', 'w'), indent=1)
