#take a roof knowing the coordinates and use it to retrieve all the others "on the same building"
import json
import requests

search_string = "Pelikanweg 51 3074 Muri b. Bern"

#Address to coordinates
params={
"type":"locations",
"searchText":search_string,
"lang":"de"}
locationsResponse = requests.get('https://api3.geo.admin.ch/rest/services/api/SearchServer', params=params)
locations = json.loads(locationsResponse.content.decode())
firstLocation = locations['results'][0]['attrs']

# you need the coordinates from other services, once you have them
coordinates=(firstLocation['y'],firstLocation['x']) # example coordinates
coordinates_str=','.join(map(str,coordinates))
tolerance=1

# this is wrong, bbox should be computed using tolerance and pixel size, but there are no problems for the
# purpose of this exercise
bbox=(coordinates[0]-tolerance, coordinates[1]-tolerance, coordinates[0]+tolerance,coordinates[1]+tolerance)
bbox_str=','.join(map(str,bbox))
# retrieve one roof and the building_id associated
params={
"geometryType":"esriGeometryPoint",
"returnGeometry":"true",
"layers":"all:ch.bfe.solarenergie-eignung-daecher",
"geometry":coordinates_str,
"mapExtent":bbox_str,
"imageDisplay":"1391,1070,96",
"tolerance":tolerance,
"order":"distance",
"lang":"de",
}
print(coordinates_str)
response_one_roof = requests.get('https://api3.geo.admin.ch/rest/services/api/MapServer/identify', params=params)
response_one_roof_decoded = json.loads(response_one_roof.content.decode())
results = (response_one_roof_decoded['results'])
for result in results:
    print(result['attributes']['building_id'])
building_id=(response_one_roof_decoded)['results'][0]['attributes']['building_id']

# use the building_id of previous request to get all roofs associated with this building_id
params = {
'layer': 'ch.bfe.solarenergie-eignung-daecher',
'searchField': 'building_id',
'contains': 'false',
'searchText': str(building_id),
'returnGeometry': 'false'
}
response_all_roofs = requests.get('https://api3.geo.admin.ch/rest/services/api/MapServer/find', params=params)
response_all_roofs_decoded = json.loads(response_all_roofs.content.decode())['results']
for roof in response_all_roofs_decoded:
    # print(roof['attributes'].keys())
    print("URL:", "https://www.uvek-gis.admin.ch/BFE/sonnendach/index.html?featureId=" + str(roof['featureId']) + "&lang=de", "Fläche:", roof['attributes']['flaeche'], "Eignung(1-5):", roof['attributes']['klasse'], "PV100:", float(roof['attributes']['gstrahlung']*0.2*0.8))