"""Simple python wrapper around the Arc GIS API"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/07_arc_gis.ipynb.

# %% auto 0
__all__ = ['get_arcgis_feature_service', 'get_arcgis_layer', 'get_arcgis_layer_last_updated', 'get_arcgis_query']

# %% ../nbs/07_arc_gis.ipynb 2
import requests
from humble_chuck.models import BaseModel
from typing import *
import pandas as pd

# %% ../nbs/07_arc_gis.ipynb 3
def get_arcgis_feature_service(
    serviceName:str,
    webadaptor:str = 'VTyQ9soqVukalItT', #defaults to HUD
    **kwargs
):
    """
    A feature service can contain datasets (for example, tables and views) with or without a spatial column. 
    Datasets with a spatial column are considered layers; those without a spatial column are considered tables. 
    A feature service allows clients to query and edit feature geometry and attributes.

    This resource provides basic information about the feature service, including the feature layers and tables that it contains, the service description, and so on.
    """
    url = f"https://services.arcgis.com/{webadaptor}/arcgis/rest/services/{serviceName}/FeatureServer/"
    r = requests.get(url,params={'f':'json'})
    return r.json()

# %% ../nbs/07_arc_gis.ipynb 7
def format_arcgis_url(
    serviceName:str,
    layerId:int=0,
    webadaptor:str = 'VTyQ9soqVukalItT', #defaults to HUD
):
    return f"https://services.arcgis.com/{webadaptor}/arcgis/rest/services/{serviceName}/FeatureServer/{layerId}/"
    

# %% ../nbs/07_arc_gis.ipynb 8
def get_arcgis_layer(
    serviceName, 
    layerId:int=0,
    webadaptor:str = 'VTyQ9soqVukalItT', #defaults to HUD
    **kwargs
):
    """
    The layer resource represents a single feature layer or a nonspatial table in a feature service. 
    A feature layer is a table or view with at least one spatial column.

    For tables, it provides basic information about the table such as its ID, name, fields, types, and templates. 
    For feature layers, in addition to the table information, it provides information such as its geometry type, min and max scales, and spatial reference. 
    Each type includes information about the type, such as the type ID, name, and definition expression. 
    Types also include a default symbol and a list of feature templates. Each feature template includes a template name, description, and prototypical feature.
    
    (source)[https://developers.arcgis.com/rest/services-reference/enterprise/layer-feature-service-.htm]
    
    
    """
    url=format_arcgis_url(serviceName,layerId,webadaptor)
    params=dict(
        returnUpdates=False,
        returnDomainNames=False,
        f='json',
    )
    

    r = requests.get(
        url, 
        params
    )
    return r.json()
    
    

# %% ../nbs/07_arc_gis.ipynb 9
def get_arcgis_layer_last_updated(
    serviceName,
    layerId=0,
    webadaptor:str = 'VTyQ9soqVukalItT', #defaults to HUD
    **kwargs
):
    layer = get_arcgis_layer(serviceName,layerId,webadaptor)
    last_edit_date = layer['editingInfo']['lastEditDate']
    return pd.Timestamp(last_edit_date,unit='ms')

# %% ../nbs/07_arc_gis.ipynb 12
def get_arcgis_query(
    serviceName:str,
    layerId:int = 0,
    webadaptor:str = 'VTyQ9soqVukalItT', #defaults to HUD
    limit:Optional[int]=None,
    where:str = '1=1',
    f:str = 'geojson',
    **kwargs
)->dict:
    url = format_arcgis_url(serviceName,layerId,webadaptor) + 'query'
    if not limit:
        count_request = requests.get(
            url,
            params = {
                "f":"json",
                "where":where,
                "returnCountOnly":True
            }
        )


        count = count_request.json()['count']
    else:
        count = limit
    data = {}
    i = 0
    while i < count:

        r = requests.get(
            url,
            params = {
                "outFields":'*',
                "outSR":'4326',
                "f":f,
                "where":where,
                "resultRecordCount":limit,
                "resultOffset":i,
                "geometryType":'esriGeometryPolygon',
            }
        )

        if i ==0:

            data = r.json()

        else:
            data['features'].extend(r.json()['features'])
        i+=1000

    return data 
