import json
import requests
import geopandas as gpd
import numpy as np
import pandas as pd
import tempfile

def importWfsByGDB(url,layer,fields,gdb):
    
    #grid_fields = 'GEOMETRY,MAINGROUP,FERTILITYCLASS,MAINTREESPECIES,VOLUME'
    #name = 'gridcell'
    #url = 'https://avoin.metsakeskus.fi/rajapinnat/v1/gridcell/ows?'
    #tempd = 'grid.json'
    tempd = tempfile.NamedTemporaryFile(prefix='grid_',suffix='.json')
    tempd = str(tempd.name)
    
    gdfs = []
    for c,(idx,polygon) in enumerate(gdb.iterrows()):
        xmin, ymin, xmax, ymax = [np.round(i,0) for i in polygon.geometry.bounds]
        grid_size = 1000
        x_coords = np.arange(xmin,xmax,grid_size)
        y_coords = np.arange(ymin,ymax,grid_size)
        for x in x_coords:
            for y in y_coords:
                bbox_string=[str(x),str(y),str(x+grid_size),str(y+grid_size)]
                bbox_string = ','.join(bbox_string)
                
                params = {'service':'wfs',
                    'request':'getFeature',
                    'typename':layer,
                    'propertyName':fields,
                    'bbox':bbox_string,
                    'outputFormat':'json',
                    'srsname':'epsg:3067'}

                respo = requests.get(url,params,allow_redirects=True)
                if respo.status_code != 200:
                    print (respo.status_code)
                    print (respo.raise_for_status())
                else:
                    respo_js = respo.json()
                    with open(tempd, "w") as outfile:
                        json.dump(respo_js,outfile)
                    g = gpd.read_file(tempd)
                    #g['name'] = polygon['name']
                    gdfs.append(g)
                    
    data = gpd.GeoDataFrame(pd.concat(gdfs, ignore_index=True))
    data

    return data